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.
<?php $pattern1 = "^hello hi$"; $pattern2 = "^h?llo hi$"; // form pattern that checks that both patterns match $pattern3 = "/".??."/"; if(preg_match($pattern3,$string)) { //solved it } ?>
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.
<?php $pattern1 = "/^hello hi$/"; $pattern2 = "/^h?llo hi$/"; if(preg_match($pattern1,$string) && preg_match($pattern2,$string)) { //solved it } ?>
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:
/^(?=PATH_1$)(?=PATH_N$).*/
So for your example it would be
/^(?=hello hi$)(?=h.llo hi$).*/