简体   繁体   中英

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

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]);
{employee([A-Za-z0-9\.]+)}(?!\s*{\/\w+})

(?!\\s*{\\/\\w+})负前瞻-断言不可能匹配下面的正则表达式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM