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;
}
Kind regards,
M.