I’m trying to make search terms bold in this search script that I’m making. The trouble is that I can’t get it to work case insensitively.
function highlight($term,$target){
$terms = explode(" ", $term);
foreach($terms as $term){
$result = (eregi_replace($term, "<strong>$term</strong>", $target));
}
return $result;
}
That is the function I have so far. It says on PHP.net that eregi_replace() is case-insensitive, but it’s obviously not working for some reason.
The
ereg_*(POSIX regular expression) functions are deprecated as of PHP 5.3 and have not been suggested for a long time. It is better to use the PCRE (preg_*) functions (such aspreg_replace).You can do so by creating a case-insensitive regular expression, and then wrapping matches in
<strong>tags:What this does is first call
preg_quoteon your$termso that if there are any characters that have meaning in a regular expression in the term, they are escaped, then creates a regular expression that looks for that term surrounded by word boundaries (\b— so that if the term is “good” it won’t match “goodbye”). The term is wrapped in parentheses to make the regular expression engine capture the term in its existing form as a “backreference” (a way for the regular expression engine to hang on to parts of a match). The expression is made case-insensitive by specifying theioption. Finally, it replaces any matches with that same backreference surrounded by the<strong>tag.If you’d like a good tutorial on regular expressions, check out the tutorial on regular-expressions.info.