I have two preg_match_all()'s running right now and I'd like to merge them into one. Each finds an occurrence of either functionA or functionB. I know to use "this|that" to match this or that, but when it comes to matching "%this()" or "%that()" I'm not sure if it's best to match "%this()|%that()" or if there's a way to bound what's included on each side of the '|' to write something short like "%this|that()", which I believe would match "%this" and "that()" but not either "this()" or "that()". I'm aware of other ways to solve my particular issue, but I (and hopefully others who find this) would love to know how to properly use "|" without having to repeat the entire string. Here's a more accurate representation:
我现在有两个preg_match_all()正在运行,我想将它们合并为一个。每个都发现functionA或functionB的出现。我知道使用“this | that”来匹配这个或那个,但是当涉及匹配“%this()”或“%that()”时,我不确定是否最好匹配“%this()| %that()“或者是否有办法约束'|'每一侧包含的内容写一些简短的东西,比如“%this | that()”,我相信它会匹配“%this”和“that()”,但不能匹配“this()”或“that()”。我知道其他方法可以解决我的特定问题,但我(并希望其他人发现这一点)会喜欢知道如何正确使用“|”无需重复整个字符串。这是一个更准确的表示:
$regex = '/%myFunc\(([0-9]+)\)/u';
$one = preg_match_all($regex, $text, $matches);
$regex2 = '/%otherFunc\(([0-9]+)\)/u';
$two = preg_match_all($regex2, $text, $matches2);
The goal is something shorter like:
目标是更短的,如:
$regex = '/%myFunc|otherFunc\(([0-9]+)\)/u';
preg_match_all($regex, $text, $matches);
1 个解决方案
#1
3
Well, you can use parentheses to group expressions and control precedence:
那么,您可以使用括号对表达式进行分组并控制优先级:
%(this|that)\(\)
if you don't want to create a new capturing group you can also use a non-capturing group for that, which is only for precedence and has no side-effects:
如果您不想创建新的捕获组,您还可以使用非捕获组,这仅用于优先级并且没有副作用:
%(?:this|that)\(\)
#1
3
Well, you can use parentheses to group expressions and control precedence:
那么,您可以使用括号对表达式进行分组并控制优先级:
%(this|that)\(\)
if you don't want to create a new capturing group you can also use a non-capturing group for that, which is only for precedence and has no side-effects:
如果您不想创建新的捕获组,您还可以使用非捕获组,这仅用于优先级并且没有副作用:
%(?:this|that)\(\)