I wrote this code, it seems to work but not quite as it should.

$search = "как твои дела"; $text = "привет, как твои дела? давай созвонимся."; $pos1 = stripos($text, $search); if ($pos1 !== false) { echo 'Найден '.$search; } 

The code above perfectly looks for the word “how are you” in the line, but if you look for the word “yes” for example, then it will find it in “come on,” but the search word “yes” itself is a separate word, and it finds it as two letters in the text.

How to write so that it was searched for words or word combinations?

  • In the text, replace the punctuation marks with spaces. In the search box add spaces at the edges of the phrase. - MAX
  • in my opinion, regular expressions are indispensable. Something like '\ b $ search \ b'. And the code finds everything right. - Adokenai

1 answer 1

From the comment:

In the text, replace the punctuation marks with spaces. In the search box add spaces at the edges of the phrase. - MAX

Implementation:

 $search = "как твои дела"; $text = "привет, как твои дела? давай созвонимся."; $text = ' ' . preg_replace("#[[:punct:]]#", ' ', $text) . ' '; if (stripos($text, ' ' . $search . ' ') !== FALSE) { echo 'Найден '.$search; } 

From the comment:

in my opinion, regular expressions are indispensable. Something like '\ b $ search \ b'. And the code finds everything right. - Adokenai

Implementation:

 $search = "как твои дела"; $text = "привет, как твои дела? давай созвонимся."; $pattern = '#\b'.$search.'\b#isu'; if (preg_match($pattern, $text)) { echo 'Найден'; } 
  • Thanks, with the regular expression is excellent, and the code is simple and works fine. - Tokwiro