Say I am requiring a user to input the certain words provided and he/will just input it on a textbox which will be validated regardless of order.I have been looking for answers for hours and I'm stuck :/
e.g. the words should be inputted are: foo, bar, green.
and I can still match it even if the order is bar green foo or green foo bar
I pretty much know the very basics of regex but I don't know how to match with this type of condition.. Any answers will be much appreciated!
This checks if you have exactly these three words in the input and nothing more:
/^(?=.*\bbar\b)(?=.*\bgreen\b)(?=.*\bfoo\b)(?:\s*\b\w+\b\s*){3}$/s
simple answer: don't use regex.
Just explode()
the input, and then check manually if the words are ok. A simple way to check if the input is good is this:
if(!array_diff(explode(' ', $input), $valid_words)) {
// input OK
}
use explode()
http://sandbox.phpcode.eu/g/59c57
<?php
$str = 'foo, bar, green';
$array = explode(',', $str);
print_r($array);
This regular expression will check if you have those words in your input:
(?=^.*?foo.*$)(?=^.*?bar.*$)(?=^.*?green.*$)^.*$
But it does not check if it does not have anything else. In general, I agree to others don't use regular expressions for this thing. Split the input and check against your dictionary.