So the problem.. I have been stuck with this one for a good month now, so please any help would be really appreciated.
I am trying to highlight words in a string, from words in an array. The problem I am having is with nested tags.
$bold=array();
$bold="tree,apple tree,orange";
$description="orange and apple tree";
For example; the result I want would be this <strong>orange</strong> and <strong>apple tree</strong>, but the result I am getting is this <strong>orange</strong> and <strong>apple <strong>tree</strong></strong>
I have cobbled together this so, but it doesn’t work as desired, so feel free to amend or trash, if my approach is incorrect.
function highlightWords($text, $words){
foreach ($words as $word){
$word = preg_quote($word);
$word = (str_replace("/","",$word));
$text = preg_replace("/(?!<.*?)(".preg_quote($word,'/').")(?![^<>]*?>)/si",'<strong>\1</strong>', $text);
}
return $text;
}
$description = highlightWords($description, $bold);
If I have understood your question correctly, this is your solution:
Example: http://www.ideone.com/at4lw
You call the function highlightWords with the initial text and an array of words to highlight. The function returns the text with the highlighted words.