如何在preg_match语句中使用"if X或X"

Lea*_*ing 5 php if-statement preg-match

我想在PHP中发表如下声明:

if(preg_match("/apples/", $ref1, $matches)) OR if(preg_match("/oranges/", $ref1, $matches)) { Then do something }

上面的每一个本身都可以正常工作,但我无法弄清楚如何使它如果其中任何一个为真,那么执行我在其下面的功能.

Mic*_*yen 19

使用|选择一个值或另一个值.你可以多次使用它.

preg_match("/(apples|oranges|bananas)/", $ref1, $matches)
Run Code Online (Sandbox Code Playgroud)

编辑:这篇文章让我很饿.


cha*_*aos 10

要对模式进行分组并将结果捕获到$matches:

preg_match('/(apples|oranges)/', $ref1, $matches)
Run Code Online (Sandbox Code Playgroud)

捕获结果的情况下对模式进行分组$matches(如果您正在进行其他括号捕获并且不希望这会干扰,则最相关):

preg_match('/(?:apples|oranges)/', $ref1, $matches)
Run Code Online (Sandbox Code Playgroud)


sle*_*man 5

简单,使用逻辑OR运算符:

if (expression || expression) { code }
Run Code Online (Sandbox Code Playgroud)

例如,在您的情况下:

if(
    preg_match("/qualifier 1/", $ref1, $matches) ||
    preg_match("/qualifier 2/", $ref1, $matches)
) {
    do_something();
}
Run Code Online (Sandbox Code Playgroud)