Emanuele Minotto
Emanuele Minotto

Reputation: 415

Catch-all Regular expression

In my PHP program I have some regular expressions defined only at run-time. How can I write a regular expression that match everything else those matches don't catch?

var_dump(preg_match("#^Bob$#", 'Bob'));
var_dump(preg_match("#^Alice$#", 'Alice'));

The regular expression I need is everything else than ^Bob$ and ^Alice$.

I tried using

var_dump(preg_match("#(?(?=(^Bob$|^Alice$))|^$|.*)#", 'John'));

but the preg_match function gave me Warning: preg_match(): Compilation failed: conditional group contains more than two branches at offset 27

Upvotes: 1

Views: 954

Answers (1)

stema
stema

Reputation: 93026

You used a condition (the first group starting with ?) with wrong syntax, thats your Warning.

But I think you don't need a conditional regex, try

 var_dump(preg_match("#^(?!(Bob|Alice)$).*#", 'John'));

I moved the Anchor ^ to the very start of the expression and $ outside the alternation, so it is valid for both alternatives.

This regex will match every string (without newline characters), that is not only "Bob" or "Alice".

Upvotes: 2

Related Questions