Page 1 of 1

single regexp to check for several words?

Posted: Sat Dec 13, 2008 4:46 am
by Apollo
Is there a way I can check for the presence of several words with a single regexp?

For example, how could I check if a string contains 'red', 'green' and 'blue'? (each at least once)

The only way I could think of was something like this: (checking for all possible orders)

Code: Select all

preg_match("/(red.*green.*blue|red.*blue.*green|green.*red.*blue|green.*blue.*red|blue.*red.*green|blue.*green.*red)/",$s);
But that's obviously dumb, I'd prefer a method that can also be used for 20 words instead of 3 :)

Re: single regexp to check for several words?

Posted: Mon Jan 05, 2009 7:15 am
by Apollo
Found a solution myself after all (using regexp with look ahead), posting just in case it may help someone else:

Code: Select all

preg_match("/(?=.*red)(?=.*green)(?=.*blue)/",$s);