2

Given the following simple function (for a PHP page) I am trying to match all the occurences of the word $marker in a long text string. I need to highlight its occurences. The function works, but it presents two problems:

1) it fails to match uppercase occurences of $marker

2) it also matches partial occurences: if $marker is "art", the function as it is also matches "artistic" and "cart".

How can I correct these two inconveniences?

function highlightWords($string, $marker){
$string = str_replace($marker, "<span class='highlight success'>".$marker."</span>", $string);
return $string;
}
Alex
  • 497
  • 5
  • 22
  • It's not a duplicate, but can't you just combine http://stackoverflow.com/questions/4366730/check-if-string-contains-specific-words and http://php.net/manual/en/function.strtoupper.php – online Thomas Jan 04 '16 at 13:30

1 Answers1

3

To solve the two problems you can use preg_replace() with a regular expression. Just add the i flag for case-insensitive search and add \b word boundaries around your search term, so it can't be part of another word, e.g.

function highlightWords($string, $marker){
    $string = preg_replace("/(\b" . preg_quote($marker, "/") . "\b)/i", "<span class='highlight success'>$1</span>", $string);
    return $string;
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • This solution matches both upper- and lower-case occurences, but it seems to return only lower case strings, transforming the original upper case. – Alex Jan 04 '16 at 13:40
  • @Alex Yes, I forgot to change that. I changed out the variable in the replace argument with `$1` which is the first capturing group, here: `(\b" . preg_quote($marker, "/") . "\b)`. So try it again and it should be as you wanted it. – Rizier123 Jan 04 '16 at 13:41
  • Great.It does work! I didn't know about the use of groups (`$1`). – Alex Jan 04 '16 at 13:46