PhearOfRayne
PhearOfRayne

Reputation: 5050

PHP regex pattern exclude if inside another pattern

How using PHP regex could a match be excluded if the pattern is inside another pattern.

The string/template being using looks like this:

{employee.name}
{history}
    {employee.name}
{/history}

The PHP regex pattern being used is this:

{employee([A-Za-z0-9\.]+)}

The problem with this pattern is that it will match {employee.name} twice. It needs to exclude the match if it's inside {history}*{/history}.

Upvotes: 0

Views: 76

Answers (2)

Kerwin
Kerwin

Reputation: 1212

{employee([A-Za-z0-9\.]+)}(?!\s*{\/\w+})

(?!\s*{\/\w+}) Negative Lookahead - Assert that it is impossible to match the regex below

Upvotes: 0

hwnd
hwnd

Reputation: 70750

One way that I find useful is to use the alternation operator in context placing what you want to exclude on the left side, (saying throw this away, it's garbage) and place what you want to match in a capturing group on the right side. You can then grab your matches from $matches[1] ...

preg_match_all('~{history}.*?{/history}|({employee[a-z0-9.]+})~si', $str, $matches);
print_r(array_filter($matches[1]));

Alternatively, you can use backtracking control verbs:

preg_match_all('~{history}.*?{/history}(*SKIP)(*F)|{employee[a-z0-9.]+}~si', $str, $matches);
print_r($matches[0]);

Upvotes: 3

Related Questions