This question has already been answered:

When searching made the text highlighting in this way

foreach ($words_arr as $word) { $str = preg_replace("/{$word}\w*/ui", "<span class='fcolor9'>\\0</span>", $str); } 

where $str is a string, $word is a word to be highlighted, $words_arr is a search query.

In general, everything works if you set it http://apteka1.net/search?q=Aspirin

But if you set it like http://apteka1.net/search?q=Aspirin +c

It turns out some kind of nonsense.

Tell me who knows where the error is.

Reported as a duplicate by members of Visman , cheops , aleksandr barakin , user194374, zRrr Jul 4 '16 at 11:46 pm .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Give the code getting $words_arr from the $words_arr of the parameter + the desired result and the current one - korytoff
  • $ words_arr = explode ("", $ _GET ['q']); - 15828
  • 2
    hoho, highlighting with regular expressions, in the trash. - Denis Kotlyarov
  • four
    You have too simple a regular list that climbs to the contents of html tags. Here ru.stackoverflow.com/questions/457806/... I gave the answer by highlighting the words in the issue. See how there is an exception for the tags entered. - Visman

2 answers 2

Yes, I do not see the point in regular season str_replace

 foreach ($words_arr as $word) { $str = str_replace($word, "<span class='fcolor9'>$word</span>", $str); } 

    Without touching the very approach to solving the problem.

    The fact is that in the Aspirin + c query, you have the character "c" Latin, which your script finds and highlights words to you - http://joxi.ru/xAeen9ef7wdVAy

    You have the same loop, respectively, after the first iteration, you have already added the selection markup in the $str variable, which it replaces in the second iteration.

    Ps. Do not forget to watch the original HTML in the browser, otherwise you will guess.