You need to search the format string:

$string = "Lorem ipsum dolor sit amet"; 

The person enters the search "sit ipsum amet" . Is it possible to check the string for the presence of these characters in the string, not in direct order?

In php, there are standard methods for searching by string, for example stristr() , but it will work only if you give the data in the exact order, and I just need something to find a match in the string and query.

How can this be implemented?

  • 2
    Break the search string into words and search for each word separately. - Visman September
  • use db or search engine like sphinx - Naumov
  • This is usually required in the database / search engines. But if you really need to PHP - break the line into words, cut off the endings, then search each word in the text with a regular form like preg_match('@(^|\s)'.preg_quote($word).'@i', ;$text) . So you can find out at the same time the relevance, if there are a lot of objects to be compared. - Goncharov Alexander

2 answers 2

Try this code here. The basics are array_intersect ()

 $string = "Lorem ipsum dolor sit amet"; $haystack = "sit ipsum amet"; $stringInArray = explode(' ', $string); $haystackInArray = explode(' ', $haystack); if(count(array_intersect($haystackInArray, $stringInArray)) == count($haystackInArray)) { // Слова из строки найдены } 

    The main idea is to break both strings (target and search) into words. And then we cycle through the array of the searched words and search for each word in the array of target words.

     function mixed_search($haystack, $needle) { $haystack_words = explode(' ', $haystack); $needle_words = explode(' ', $needle); foreach ($needle_words as $word) { if (array_search($word, $haystack_words) === false) return false; } return true; } $string = "Lorem ipsum dolor sit amet"; $search = "sit ipsum amet"; echo mixed_search($string, $search); 
    • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky