I am trying to highlight words in a text by using pregreplace. The words are within an array which I do feed into pregreplace. This used to work, but stopped maybe due to upgrading php in the past, now it returns nothing.
// Function highlights $words in $str
function highlight_words($str, $words) {
global $color;
if(is_array($words)) {
foreach($words as $k => $word) {
// $pattern[$k] = "~\b($word)\b~is";
$pattern[$k] = "/$word/";
$replace[$k] = '<span style="background: '.$color[2].';color:'.$color[4].';">\\1</span>';
}
}
else {
$pattern = "~\b($words)\b~is";
$replace = '<span style="background: '.$color[2].';color:'.$color[4].';">\\1</span>';
}
return preg_replace($pattern,$replace ,$str);
}
echo highlight_words($text, $words);
values of pattern:
Array
(
[0] => /$18.5mUSD/
[1] => /$8,000,000.00/
[2] => /(at)/
[3] => /+43 688 649 45702/
...
values of $replace:
Array
(
[0] => <span style="background: #FF6B02;color:#FFFFFF;">\1</span>
[1] => <span style="background: #FF6B02;color:#FFFFFF;">\1</span>
[2] => <span style="background: #FF6B02;color:#FFFFFF;">\1</span>
[3] => <span style="background: #FF6B02;color:#FFFFFF;">\1</span>
...
preg_replace simply returns nothing. Seems to be a problem with array, but the syntax looks ok. If I change preg_replace to replace some simply regex pattern it will do, but it does not work with the array.
How can this be fixed?