Search code examples
phpregexpreg-match

Using regex to match a specific pattern


I'm trying to match any strings that doesn't start with "false1" or "false2", and ends with true, but the regex isn't matching for some reason. What am I doing wrong?

$text = "start true";
$regex = "~(?:(^false1|false2).+?) true~";
if (preg_match($regex, $text, $match)) {

echo "true";    

}

Expected Result:

true

Actual Result:

null

Solution

  • You may use negative lookahead.

    ^(?!false[12]).*true$
    

    If you really want to use boundaries then try this,

    ^(?!false[12]\b).*\btrue$
    

    DEMO

    Update:

    ^(?!.*false[12]\b).*\btrue$
    

    (?!.*false[12]\b) negative lookahead which asserts that the string would contain any char but not the sub-string false1 or false2 and it must ends with the string true, that's why we added true$ at the last.