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

前端 未结 7 1387
予麋鹿
予麋鹿 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 21:18

    If your patterns don't contain many whitespaces, another option would be to eschew the arrays and use the /x modifier. Now your list of regular expressions would look like this:

    $regex = "/
    pattern1|   # search for occurences of 'pattern1'
    pa..ern2|   # wildcard search for occurences of 'pa..ern2'
    pat[ ]tern| # search for 'pat tern', whitespace is escaped
    mypat       # Note that the last pattern does NOT have a pipe char
    /x";
    

    With the /x modifier, whitespace is completely ignored, except when in a character class or preceded by a backslash. Comments like above are also allowed.

    This would avoid the looping through the array.

提交回复
热议问题