5

im making a simple word game with php and regex, how can we search that if a string have to require two or more words?

lets say

"cat"
"dog"
"play" x 2

if

"cat dog play play" pass

"hello a cat dog playing a play" not pass, only 1 "play"

"cat" not pass, no dog and 2x play

"i want a cat and a dog play with me and play with grandfather" pass

how can we match it with regex?

Adam Ramadhan
  • 22,712
  • 28
  • 84
  • 124
  • Why don't you solve it with 3 regexes instead of one? It would be much easier. I doubt it's possible with one. – JohnB Jun 03 '12 at 12:42
  • yeah i can do something like `if(preg_match("dog") && preg_match("etc") && ... )` but will it affect the performance? if i match alot of things? – Adam Ramadhan Jun 03 '12 at 12:45
  • Possible duplicate: http://stackoverflow.com/questions/10832519/regex-match-at-least-two-search-terms – Todd A. Jacobs Jun 03 '12 at 12:46
  • 2
    @JohnB Of course it’s *possible*. It just isn’t very nice to look at. – tchrist Jun 03 '12 at 14:27

2 Answers2

8

The regex you're looking for is:

/(?=.*?\bcat\b)(?=.*?\bdog\b)(?=(.*?\bplay\b){2})^.*$/

Explanation: I believe words cat, dog and play (twice) can appear in the text in any order but they must all be present in the sentence to qualify. Above regex is using positive lookahead to make sure the presence of above conditions.

Here is the online working demo of above RegEx

anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Try preg_match_all(/cat.+dog(.+play){2}/i,$str,$out);

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67