Jump to content

[SOLVED] preg_replace only outside xhtml tags


mikkelwe

Recommended Posts

I'm working a some code to highlight all occurences of a specific word on a web page. The XHTML code for the web page is stored in a mySQL database. I'm putting a pair of tags around occurences of the word that will apply a CSS class that highlights all occurences of that word. Obviously I only want to tag occurences _outside_ XHTML tags. For example I don't want to accidently put tags around the <body> tag when tagging all occurences of 'body' in the text. My problem seems to be that I don't know how to effeciently compensate for the lack of variable-length look-around in the PHP regex engine. So far I've come up with the following piece of code that works but I'm afraid it's rather inefficient. Below $class is the name of the CSS class. $word is what I'm tagging and $body[1] is the XHTML source code extracted from the database.
[tt]
    $pattern = '/(\>[^\<]+)(' . preg_quote($word) . ')/iU';
    $replacement = '${1}<span class="' . $class . '">${2}</span>';
    while (($tmp = preg_replace($pattern, $replacement, $body[1])) != $body[1])
        $body[1] = $tmp;
[/tt]
Any help would be appreciated.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.