Highlighting an accented search term using preg_replace

Viewed 43

I've been trying to bold a search term in a sentence. If the sentence is Engliš is spoken wörldwide. If my search term is spoken world I want to get Engliš is <b>spoken wörld</b>wide.

I've used this function:

function highlightWords($text, $searchTerm){
   $corr = ['a' => '[aäâ]', 'o' => '[oöòóôõ]', 'c' => '[cç]', 's' => '[şśšșŝ]', 'y' => '[ýÿŷȳy]', 'o' => '[ôöòóøōoõ]', 'n' => '[ñńňn]',  'u' => '[üu]'];
   $key = preg_quote($searchTerm);
   $pattern = '/' . strtr($key, $corr) . '/iu';
   $text = preg_replace($pattern, '<b>$0</b>', $text);
   return $text;
}

It supposed to work, but I get really strange behavior. Few examples are:

Text is Sygmaý çykdy deşdi-sähra düzünden (sorry for the weird sentence). When $searchTerm is duz it perfectly works, I get Sygmaý çykdy deşdi-sähra <b>düz</b>ünden. If I change search term to sahra, the function returns just plain Sygmaý çykdy deşdi-sähra düzünden.

Works with cykdy and çykdy.

But doesn't work with neither sygmay nor sygmaý. But works with Sygmaý with capital letter.

What should I need to fix in order to get highlighted search term in all scenarios?

1 Answers

There are a couple of problems in the function, specifically in the $corr array.

First, there are two "o" sections, and they are different. Those need to be combined. Second, the unaccented letter must be in the array for each letter. s does not have this, the missing "s" is what is causing this particular failure.

Fixed function:

function highlightWords($text, $searchTerm)
{
    $corr    = [
        'a' => '[aäâ]', 
        'o' => '[oöòóôõøō]', 
        'c' => '[cç]', 
        's' => '[sşśšșŝ]', 
        'y' => '[yýÿŷȳ]', 
        'n' => '[nñńň]', 
        'u' => '[uü]'
    ];
    $key     = preg_quote($searchTerm);
    $pattern = '/' . strtr($key, $corr) . '/iu';
    $text    = preg_replace($pattern, '<b>$0</b>', $text);
    return $text;
}

$input = 'Sygmaý çykdy deşdi-sähra düzünden';
$term  = 'sahra';

$expected = 'Sygmaý çykdy deşdi-<b>sähra</b> düzünden';

$highlighted = highlightWords($input, $term);

assert($highlighted == $expected, 'Term should be marked bold');
echo $highlighted . PHP_EOL;
Related