Alex Alex - 4 years ago 164
PHP Question

regex string substitution upper and lower case

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;
}

Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download