phpstringreplacecpu-wordcase-insensitive

Case-insensitive match multiple search words in text and wrap them in <strong> HTML tags


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.


Solution

  • 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 as preg_replace).

    You can do so by creating a case-insensitive regular expression, and then wrapping matches in <strong> tags:

    function highlight($term, $target)
    {
      $terms = array_unique(explode(" ", $term)); // we only want to replace each term once
      foreach ($terms as $term)
      {
        $target = preg_replace('/\b(' . preg_quote($term) . ')\b/i', "<strong>$1</strong>", $target);
      }
    
      return $target;
    }
    

    What this does is first call preg_quote on your $term so 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 the i option. Finally, it replaces any matches with that same backreference surrounded by the <strong> tag.

    $string = "The quick brown fox jumped over the lazy dog. The quicker brown fox didn't jump over the lazy dog.";
    $terms = "quick fox";
    highlight($terms, $string);
    // results in: The <strong>quick</strong> brown <strong>fox</strong> jumped over the lazy dog. The quicker brown <strong>fox</strong> didn't jump over the lazy dog.
    

    If you'd like a good tutorial on regular expressions, check out the tutorial on regular-expressions.info.