wildabenny wildabenny - 1 month ago 6
PHP Question

Searching page and replacing some elements

I have 2 sets of tags on page, first is

{tip}tooltip text{/tip}


and second is

{tip class="someClass"}tooltip text{/tip}


I need to replace those with

<span class=„sstooltip”><i>?</i><em>tooltip text</em></span>


I dont know how to deal with adding new class to the
<span>
tag. (The tooltip class is always present)

This is my regex
/\{tip.*?(?:class="([a-z]+)")?\}(.*?)\{\/tip\}/
.

I guess I need to check array indexes for class value, but those are different, depending on {tip} tag version. Do I need two regular expressions, one for each version, or there is some way to extract and replace class value?

php code:

$regex = "/\{tip.*?(?:class=\"([a-z]+)\")?\}(.*?)\{\/tip\}/";
$matches = null;
preg_match_all($regex, $article->text, $matches);

if (is_array($matches)) {
foreach ($matches as $match) {
$article->text = preg_replace(
$regex,
"<span class=tooltip \$1"."><i>?</i><em>"."\$2"."</em></span>",
$article->text
);
}
}

Answer

Here's your answer (I've also made it a bit more robust):

{tip(?:\s+class\s*=\s*"([a-zA-Z\s]+)")?}([^{]*){\/tip}

PCRE (which PHP uses, if memory serves) will automatically pick up that the first capture group (which grabs the classes) is empty in the first case, and just substitute the empty string in the replacement. The second case is self-explanatory.

Your replacement code, then, will look like this:

$article->text = preg_replace(
    '/{tip(?:\s+class\s*=\s*"([a-zA-Z\s]+)")?}([^}]*){\/tip}/',
    '<span class="tooltip $1"><i>?</i><em>$2</em></span>',
    $article->text
);

Yout don't need to check if the regex matches beforehand - that's implied by preg_replace, which is performing a regex match and then replacing any text matched by the pattern with that text. If there are no matches, no replacement occurs.

Comments