How do you perform a preg_match where the pattern is an array, in php?

前端 未结 7 1386
予麋鹿
予麋鹿 2020-12-16 20:41

I have an array full of patterns that I need matched. Any way to do that, other than a for() loop? Im trying to do it in the least CPU intensive way, since I will be doing

7条回答
  •  春和景丽
    2020-12-16 20:55

    You can combine all the patterns from the list to single regular expression using implode() php function. Then test your string at once using preg_match() php function.

    $patterns = array(
      'abc',
      '\d+h',
      '[abc]{6,8}\-\s*[xyz]{6,8}',
    );
    
    $master_pattern = '/(' . implode($patterns, ')|(') . ')/'
    
    if(preg_match($master_pattern, $string_to_check))
    {
      //do something
    }
    

    Of course there could be even less code using implode() inline in "if()" condition instead of $master_pattern variable.

提交回复
热议问题