Question

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.

Était-ce utile?

La solution

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

Autres conseils

Try it like this:

<?php

$string = 'Lets locate red apple, or even, apple red!';

$search = 'red apple';

$search_parts = ( strpos( ' ', $search ) !== false ) ? explode( ' ', $search ) : array( $search );

preg_match_all( '#(' . preg_quote(  implode( ' ', $search_parts ), '#' ) . ')|(' . preg_quote( implode( ' ', array_reverse( $search_parts ) ), '#' ) . ')#i', $string, $matches );

echo '<pre>' ;
print_r( $matches[0] );
echo '</pre>' ; 

?>

Notice the use of strpos() and preg_quote() usage in order to avoid regex pattern errors.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top