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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.