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 ?
    – Rizier123
    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

2
  • 1
    I tried this preg_match('^(?=.*?\bcat\b)(?!.*?\bdog\b).*$', $str) but I am getting an error: No ending delimiter '^' found
    – littleibex
    Commented May 4, 2015 at 14:18
  • You have to use: preg_match('/^(?=.*?\bcat\b)(?!.*?\bdog\b).*$/', $str);
    – anubhava
    Commented May 4, 2015 at 14:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.