开发者

How to Use an "if X or X" in a preg_match Statement

I'm looking to make a statement in PHP like this:

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

Each of those above by themselves work just fine, but I ca开发者_JAVA百科n't figure out how to make it so that if either of them is true, then to perform the function I have beneath it.


Use the | to select one value or the other. You can use it multiple times.

preg_match("/(apples|oranges|bananas)/", $ref1, $matches)

EDIT: This post made me hungry.


To group your patterns and capture the result in $matches:

preg_match('/(apples|oranges)/', $ref1, $matches)

To group your patterns without capturing the result in $matches (most relevant if you're doing other parenthesis capturing and don't want this to interfere):

preg_match('/(?:apples|oranges)/', $ref1, $matches)


Simple, use the logical OR operator:

if (expression || expression) { code }

For example, in your case:

if(
    preg_match("/qualifier 1/", $ref1, $matches) ||
    preg_match("/qualifier 2/", $ref1, $matches)
) {
    do_something();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜