ratherBeKiting
ratherBeKiting

Reputation: 275

Combining Regex using preg_match

I currently have 2 regular expressions to match. I need to match either of them

I am currently using this code:

$string = '000.400.101';

$regex1 = "^(000\.000\.|000\.100\.1|000\.[36])";
$regex2 = "^(000\.400\.0|000\.400\.100)";

$result = (preg_match('/'.$regex1.'/', $string) ||
           preg_match('/'.$regex2.'/', $string)) ? 1 : 0 ;

I would like to shorten this and clean it up a little. Would the below be equivalent:

$result = (preg_match('/'.$regex1.'|'.$regex2.'/', $string)) ? 1 : 0 ;

Upvotes: 0

Views: 56

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

You can try consolidating everything into the following single regex:

000\.(?:[36]|000\.|100\.1|400\.(?:0|100))

Demo

$result = preg_match('/000\.(?:[36]|000\.|100\.1|400\.(?:0|100))/', $string) ? 1 : 0;

And here is a link to a demo in PHP showing that the code works.

By the way, if you have the general need to regex match IP addresses, I think this general problem should be very well covered already on Stack Overflow and within PHP, and you should search around for something which might help you.

Upvotes: 3

Related Questions