Search code examples
phpwebsearchhighlightcase-sensitive

There is an PHP function to HightLight a word in a string but not case sensitive/accent sensitive?


There is a PHP function that can highlight a word regardless of case or accents, but the string returned will be the original string with only the highlighting? For example:

Function highlight($string, $term_to_search){
// ...
}
echo highlight("my Striñg", "string")
// Result: "my <b>Striñg</b>"

Thanks in advance!

What I tried:

I tried to do a function that removed all accents & caps, then did a "str_replace" with the search term but found that the end result logically had no caps or special characters when I expected it to be just normal text but highlighted.


Solution

  • You can use ICU library to normalize the strings. Then, look for term position inside handle string, to add HTML tags at the right place inside original string.

    function highlight($string, $term_to_search, Transliterator $tlr) {
        $normalizedStr = $tlr->transliterate($string);
        $normalizedTerm = $tlr->transliterate($term_to_search);
    
        $termPos = mb_strpos($normalizedStr, $normalizedTerm);
        // Actually, `mb_` prefix is useless since strings are normalized
    
        if ($termPos === false) { //term not found
            return $string;
        }
    
        $termLength = mb_strlen($term_to_search);
        $termEndPos = $termPos + $termLength;
        
        return
            mb_substr($string, 0, $termPos)
            . '<b>'
            . mb_substr($string, $termPos, $termLength)
            . '</b>'
            . mb_substr($string, $termEndPos);
    }
    
    $tlr = Transliterator::create('Any-Latin; Latin-ASCII; Lower();');
    
    echo highlight('Would you like a café, Mister Kàpêk?', 'kaPÉ', $tlr);