Reputation: 110
I need to create a php regex pattern that would return true if one or more certain words are in the string, but a number of others are not.
For example, let's say we want to allow the words 'and', 'this', 'then'; but then disallow the words 'dont', 'worry' and 'never'.
So the following sentences should be matches: "I like this stuff" "this and then" "is then" "me and you"
but the following should not: "I never like this stuff" "dont worry about it" "dont worry about this and that" "I never worry about that stuff" "I never do something"
The real stickler is not just the combination of 'and' 'or' 'and not' operators, but also that the words/strings could come anywhere in the sentence.
Thanks for your help
Upvotes: 2
Views: 1965
Reputation: 386706
"And" and "not" are harder to do with regex. It's can be easier to it using more than one
preg_match('/\b(?:and|this|then)\b/i', $str)
&&
!preg_match('/\b(?:dont|worry|never)\b/i', $str)
But it can be done.
First, the negation:
preg_match('/\b(?:and|this|then)\b/i', $str)
&&
!preg_match('/^(?: (?!\b(?:dont|worry|never)\b). )*\z/isx', $str)
Then combining them:
preg_match(
'/
^
(?= .* \b(?:and|this|then)\b )
(?= (?: (?!\b(?:dont|worry|never)\b). )*\z )
/isx',
$str
)
This works in Perl. Not tested in PHP.
Update: PHP-ified the code. Removed stray slash.
Upvotes: 2
Reputation: 48887
function isAllowedSentence($str)
{
return (preg_match('/\b(and|this|then)\b/i', $str) && !preg_match('/\b(don\'t|worry|never)\b/i', $str));
}
echo isAllowedSentence('I like this stuff'); // true
echo isAllowedSentence('I never like this stuff'); // false
echo isAllowedSentence('I like Johnny Mathis'); // false
Upvotes: 5