0

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?

merlin
  • 2,717
  • 3
  • 29
  • 59
  • 1
    You need to escape any characters that have special meaning `$ + .` etc. in the pattern: `$pattern[$k] = "/" . preg_quote($word, "/") . "/";` – AbraCadaver Feb 21 '19 at 19:00
  • Also, there is no word boundary between spaces and `$` or `(`. Use `$pattern = "~(?<!\w)($words)(?!\w)~is"` instead of `$pattern = "~\b($words)\b~is"`. – Wiktor Stribiżew Feb 21 '19 at 19:18

0 Answers0