php regex must contain several words and must not contain others
I need to create a php regex pattern that would return true if one or more certain words are in the string, 开发者_JAVA技巧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
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
"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.
精彩评论