Reputation: 3124
I have a list of words (in array) to be highlighted in string ( $text ) .Here is my code
$text = " A string with a spans and color highlighted";
$words = array('and','span');
foreach($words as $word){
$patterns[] = '/'.$word.'/i';
}
foreach($words as $word){
$replacements[] = "<span style='color:red;font-weight:bold;'>".$word."</span>";
}
echo preg_replace($patterns, $replacements, $text);
I want to replace words span and color from a $text, but the result is something different, it also replacing the html tag span. How can i overcome this issue . or can i have alternative to this.
You can reproduce problem here. http://writecodeonline.com/php/
Thanks in advance.
Upvotes: 0
Views: 65
Reputation: 2097
Here is a simplier solution, using explode
function:
$text = "A string with a span and color highlighted";
$words = array('and','span');
$exploded = explode(" ", $text);
$i = 0;
foreach ($exploded as $word) {
if (in_array($word, $words)) {
$exploded[$i] = "<span style='color:red;font-weight:bold;'>".$word."</span>";
}
$i++;
}
print_r($exploded);
RESULT:
Array
(
[0] => A
[1] => string
[2] => with
[3] => a
[4] => <span style='color:red;font-weight:bold;'>span</span>
[5] => <span style='color:red;font-weight:bold;'>and</span>
[6] => color
[7] => highlighted
)
Upvotes: 0
Reputation: 89547
You don't need to produce a pattern and a replacement string for each word of the list. You only need to build one pattern and one replacement string with a backreference:
$text = " A string with a span and color highlighted";
$words = array('and', 'span');
$pattern = '~\b(?:' . implode('|', $words) . ')\b~';
$replacement = '<span style="color:red;font-weight:bold;">$0</span>';
$result = preg_replace($pattern, $replacement, $text);
In the replacement string the backreference $0
refers to the whole match result.
Since you parse the string only once, you avoid the problem.
Upvotes: 1