PREG_MATCH check all words and condition

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.

Asked By: developer
||

Answer #1:

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 !!!

Answered By: Wiktor Stribiżew

Answer #2:

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
Answered By: splash58
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles