1

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
4
  • Throw your regex into: regex101.com and look at the explanation to the right. Then you will see what your regex really does. (^(?<!false1|false2)(.*?)true$) Commented Oct 21, 2015 at 2:12
  • @Rizier123 Is that regex in your comment a solution or...? Because it doesn't match correctly. Commented Oct 21, 2015 at 2:17
  • @Rizier123 Also, I already know about that website, and knowing what it does, doesn't help me figure out how to fix it. Commented Oct 21, 2015 at 2:18
  • @Rizier123 Well, I assume you didn't trying matching with starting of "false1" and "false2"? Because it echos there too. Commented Oct 21, 2015 at 2:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

But if the $text is something like "start false1 true", it also echos.
I'm trying to match any strings that doesn't start with "false1" or "false2" . But the above does'nt starts with false1.
I don't want it to match ANY string that has false1, or false2 followed by true. Sorry if I wasn't really clear with that.
try ^(?!.*false[12]\b).*\btrue$
It works. But it's a really complex regex, and there's some part that I don't understand. Can you break it down, and explain it in the answer above, please? Thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.