Search code examples
phpregextext-search

PHP and two-directional text searching


Given a text file with many strings.

If, for example, do a search for red apples, the following code:

$search = "red apples";
$contents = file_get_contents("file.txt");
$pattern = "/^.*$search*\$/m";
preg_match_all($pattern, $contents, $matches);
implode("\n", $matches[0]);

will return (along with other strings) the following one:

Plate with many red apples blah blah

I need to found the same string, but with searching for apples red. Are there any ways to do it?

Thanks.


Solution

  • $search_inversed = implode(' ', array_reverse(explode(' ', $search)));