Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Highlighting an accented search term using preg_replace

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!