0

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}.

2 Answers 2

3

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]);
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.