5

Ok lets say I whant to match 3 words in a sentence... but I neet to match them in any order, for example:

$sentences = Array(
   "one two three four five six seven eight nine ten",
   "ten nine eight seven six five four three two one",
   "one three five seven nine ten",
   "two four six eight ten",
   "two ten four six one",
);

So I need to match the words "two", "four" & "ten", but in any order and they can or not have any other words between them. I Try

foreach($sentences AS $sentence) {
   $n++;
   if(preg_match("/(two)(.*)(four)(.*)(ten)/",$sentence)) {
       echo $n." matched\n";
   }
}

But this will match ONLY sentence 1 and I need to match in sentence 1,2,4 & 5.

I hope you can help... Regards! (and sorry for my english)

Juan Carlos
  • 67
  • 1
  • 8
  • 1
    [try this...](http://stackoverflow.com/questions/3533408/regex-i-want-this-and-that-and-that-in-any-order) it's not for php but it is for regex... [and actual documentation](http://www.regular-expressions.info/lookaround.html) – gloomy.penguin Oct 10 '14 at 23:37
  • 3
    also... you [may not need regex](http://xkcd.com/1171/) for this... just check to see if the string contains the other strings. http://stackoverflow.com/questions/4366730/how-to-check-if-a-string-contains-specific-words – gloomy.penguin Oct 10 '14 at 23:40

1 Answers1

6

You could use Positive Lookahead to achieve this.

The lookahead approach is nice for matching strings that contain these substrings regardless of order.

if (preg_match('/(?=.*two)(?=.*four)(?=.*ten)/', $sentence)) {
    echo $n." matched\n";
}

Code Demo

hwnd
  • 69,796
  • 4
  • 95
  • 132