This question already has an answer here:
I want a match only if the string milk
is not preceded at any time by any or all of 4 specific words (for simplicity call these words AA, BB, CC, DD).
So I went to the store and bought some milk
would match but the following wouldn't:
AA went to the store and bought some milk
or BBCCDDmilk
Put another way, how do I get the opposite response of: /.*?(AA|BB|CC|DD).*?milk/
I think I'm supposed to put a caret somewhere but haven't been able to figure it out. Thank you.
</div>
This regex will validate each line in the given text to ensure it doesn't have the string {aa, bb, cc, dd} preceding the string milk on any single line. Matching lines are then returned. Note: the examples in OP show that the matched "words" are simply strings, and white space and word boundaries do not matter.
^(?!.*?(?:AA|BB|CC|DD).*?milk).*
^
anchor this match to the start to of the line(?!
start negative look ahead, if my contents match successfully then I'll fail.*?(?:AA|BB|CC|DD).*?milk
look for strings aa bb cc dd followed by string milk)
end the lookahead.*
match the entire sentenceInput Text
AA went to the store and bought some milk
BBCCDDmilk
I went to the store and bought some milk
Aardvarks like milk
Code
<?php
$sourcestring="your source string";
preg_match_all('/^(?!.*?(?:AA|BB|CC|DD).*?milk).*/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
Matches
$matches Array:
(
[0] => Array
(
[0] => I went to the store and bought some milk
)
)