replacing keywords but NOT within element's attribute value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Integralist
Forum Newbie
Posts: 1
Joined: Mon May 04, 2009 8:47 am

replacing keywords but NOT within element's attribute value

Post by Integralist »

Hi,

I have some HTML code, and what I'm trying to do is wrap any words that are thought to be 'keywords' in <strong> tags.

I posted this on another forum and managed to get further along with it but the other person seems to have become unresponsive so I'm posting here in the hope that someone else can help.

I was having issues with my script which was wrapping not just the keywords but the keywords within an <A> element's attributes (e.g. wrapping certain words within the TITLE and ALT attributes).

The poster on the other forum helped resolve this issue, but it only seems to work with a hard coded array of keywords. Where as my keywords come from a database. I've tried to work around this (see code below) but it doesn't work.

Any help appreciated.

Code: Select all

 
private function replaceKeywords()
        {
            // Make an Array from the keywords string (e.g. "this, is, my, list, of, keywords")
            $keywords = explode(', ', $this->_articleKeywords);
 
            // make sure the keywords array is formatted like a regular expression pattern (e.g. wrapped in forward slashes)
            foreach ($keywords as $key => $value) {
                $this->_updatedKeywords[$key] = "/\b$value\b/i"; // the pattern is case insensitive, and should only match whole words
            }
 
            // Store the article content
            $text = $this->_articleContent;
 
            // Create a regular expression pattern that will ignore element attributes
            $pattern = '#(^|>)[^<]+#';
 
            function replacement($textChunk)
            {
                return preg_replace($this->_updatedKeywords, '<i style="color:green;"><b>\0</b></i>', $textChunk[0]);
            }
 
            $text = preg_replace_callback($pattern, 'replacement', $text);
 
            return $text;
        }
 
Remember, if in the function "replacement()" I use a hard coded Array then this works fine, but I can't use a hard coded Array here because the data is coming from my database and is unknown until the script is run.

Kind regards,

M.
Last edited by Benjamin on Mon May 04, 2009 9:26 am, edited 1 time in total.
Reason: Changed code type from text to php.
Post Reply