Skip to content
Advertisement

Regex validation matching pattern1 and pattern2 in PHP

I need to match a string against two patterns both patterns must match the string. You could imagine it as some sort of validation chain.

Patterns in below code are just examples.

JavaScript

I know code below is a possible solution, but I’m interested to know can it be done with one preg_match by joining patterns together somehow.

JavaScript

Advertisement

Answer

You can use a positive lookahead to make sure the string matches all the patterns you want, before retrieving the value. Something like:

JavaScript

So for your example it would be

JavaScript

DEMO

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement