3

How can I check using PHP regular expressions, whether my string variable $str contains the word 'cat' but does not contain the word 'dog'.

  • Case 1: $str = "My pet: parrot" -> Output: false
  • Case 2: $str = "My pet: dog and cat" -> Output: false
  • Case 3: $str = "My pet: cat" -> Output: true

I have tried this and it works but I was wondering if there was a single regular expression to do it

$str = "My pet: dog and cat";
if (preg_match('/(\bdog\b)/', $str) && !preg_match('/(\bcat\b)/', $str)) echo 'TRUE';
else echo 'FALSE';
1
  • Have you tried something ? Commented May 4, 2015 at 14:19

1 Answer 1

6

You can use a negative and a positive lookahead for this:

^(?=.*?cat)(?!.*?dog).*$

To check for complete words use \b:

^(?=.*?\bcat\b)(?!.*?\bdog\b).*$

RegEx Demo

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

2 Comments

I tried this preg_match('^(?=.*?\bcat\b)(?!.*?\bdog\b).*$', $str) but I am getting an error: No ending delimiter '^' found
You have to use: preg_match('/^(?=.*?\bcat\b)(?!.*?\bdog\b).*$/', $str);

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.