I've written a regular expression which seraches the search terms in OR condition, such that provided three words have in string irrespective of their order. Now i want to just put an AND condition as I want to get ALL THREE words simulatniously in a string with different order.
Here's my preg_match()
regular expresison.
$myPregMatch = (preg_match("/\b^(Word1|Word2|Word3)\b/", "Word4 Word2 Word1 Word3 Word5 Word7"));
if ($myPregMatch){
echo "FOUND !!!";
}
I want to find in string "Word4 Word2 Word1 Word3 Word5 Word7"
that all words are in it with different order. and if sample string is "Word5 Word7 Word3 Word2"
then it shouldn't returns.
You need anchored look-aheads:
^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)
See demo
If there are newline symbols in the input string, you need to use an /s
modifier.
Here is an IDEONE demo:
$re = '/^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)/';
$str = "Word4 Word2 Word1 Word3 Word5 Word7";
$myPregMatch = (preg_match($re, $str));
if ($myPregMatch){
echo "FOUND !!!";
}
Result: FOUND !!!
it maybe faster to check every word
$string = "Word4 Word2 Word1 Word3 Word5 Word7"; // input string
$what = "Word2 Word1 Word3"; // words to test
$words = explode(' ', $what); // Make array
$i = count($words);
while($i--)
if (false == strpos($string, $words[$i]))
break;
$result = ($i==-1); // if $i == -1 all words are present in input string