0

What I am trying to achieve is - I want to use a preg-replace to highlight searched string in suggestions but ignoring diacritics on characters, spaces or apostrophe. So when I will for example search for ha my search suggestions will look like this:

  • O'Hara
  • Ó an Cintighe
  • H'aSOMETHING

I have done a loads of research but did not come up with any code yet. I just have an idea that I could somehow convert the characters with diacritics (e.g.: Á, É...) to character and modifier (A+´, E+´) but I am not sure how to do it.

Juraj.Lorinc
  • 503
  • 6
  • 26
  • possible duplicate of [How to remove diacritics from text?](http://stackoverflow.com/questions/1770250/how-to-remove-diacritics-from-text) – Tomasz Kowalczyk Jan 13 '15 at 21:58
  • But I don't want to remove diacritics-i just want to "ignore" it with regex. – Juraj.Lorinc Jan 13 '15 at 22:14
  • You can remove diacritics and work with the string with all the diacritics removed. PCRE doesn't provide "character equivalent" feature. – nhahtdh Jan 14 '15 at 03:02
  • I thought about that as well but the thing is I need to display the words with diacritics just with highlighted (bold) part of the string. – Juraj.Lorinc Jan 14 '15 at 09:10
  • Can someone remove the "This question may already have an answer here:" text? It is not right. The person who put it there clearly misunderstood my question. – Juraj.Lorinc Jan 25 '15 at 11:14

1 Answers1

-1

I finally found working solution thanks to this Tibor's answer here: Regex to ignore accents? PHP

My function highlights text ignoring diacritics, spaces, apostrophes and dashes:

  function highlight($pattern, $string)
  {
    $array = str_split($pattern);

    //add or remove characters to be ignored
    $pattern=implode('[\s\'\-]*', $array);  

    //list of letters with diacritics
    $replacements = Array("a" => "[áa]", "e"=>"[ée]", "i"=>"[íi]", "o"=>"[óo]", "u"=>"[úu]", "A" => "[ÁA]", "E"=>"[ÉE]", "I"=>"[ÍI]", "O"=>"[ÓO]", "U"=>"[ÚU]");

    $pattern=str_replace(array_keys($replacements), $replacements, $pattern);  

    //instead of <u> you can use <b>, <i> or even <div> or <span> with css class
    return preg_replace("/(" . $pattern . ")/ui", "<u>\\1</u>", $string);
  }
Community
  • 1
  • 1
Juraj.Lorinc
  • 503
  • 6
  • 26
  • What about `àÀâÂèÈêÊëËîÎïÏôÔùÙüÜçÇ`? Just talking for french diacritics. – Toto Jan 14 '15 at 12:44
  • Sure, but I just say that for you, you'd better change your answer, it isn't my problem, I already know how to deal with. – Toto Jan 14 '15 at 13:35
  • It is not working when string have diacritics and the search key also have diacritics – Kishor Patidar Dec 13 '20 at 19:44