PHP正则表达式模式排除在其他模式中


PHP regex pattern exclude if inside another pattern

如果模式在另一个模式中,如何使用PHP正则表达式排除匹配。

正在使用的字符串/模板如下所示:

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

使用的PHP正则表达式模式如下:

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

此模式的问题在于它将与{employee.name}匹配两次。如果它在{history}*{/history}内部,则需要排除匹配。

我发现有用的一种方法是在上下文中使用交替运算符,将要排除的内容放在左侧(扔掉它,这是垃圾(,并将要匹配的内容放置在右侧的捕获组中。然后您可以从$matches[1]获取您的比赛。。。

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

或者,您可以使用回溯控制动词:

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+})否定前瞻-断言不可能匹配下方的正则表达式