0

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:

$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);
thatthatisis
  • 783
  • 7
  • 18

1 Answers1

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)\(\)
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Well, that's terribly simple. I didn't think it worked since parenthesis usually encase subject matches. Are the parenthesis just interpreted differently in this case or will it create a subject match? – thatthatisis Mar 05 '13 at 22:06
  • Joey, this works and thank you much, but I'm wondering if you know a way to do this without creating a subject match for "this" or "that". – thatthatisis Mar 05 '13 at 22:19
  • 2
    You mean non-capturing group? http://stackoverflow.com/questions/3512471/non-capturing-group – zanegray Mar 05 '13 at 22:28