single regexp to check for several words?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

single regexp to check for several words?

Post 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 :)
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: single regexp to check for several words?

Post 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);
Post Reply