Problem with or in Regexp


Problem with or in Regexp

我有这个Regexp:

/'{%'s([^else|endloop|endif][a-z0-9'.'|_]+)'s%'}/si

我在preg_replace中使用这个regexp。这个标记:

{# comment %}
{# comment number 2$% %}
{% variable %}
{% array.key1.key2 %}
{% array.key1.key2|escape|bold %}
{% variable|escape %}
{% loop array as item %}
    My item is {% item.text %}
{% endloop %}
{% if (something): %}
    do something truly
{% else: %}
    nothing to do
{% endif; %}

为什么这个regexp不是为{% item.text %}工作,而是与其他工作?我想我在这里写错了[^else|endloop|endif]

我做错了什么?

我想你可能是想:

/'{%'s((?!(else|endloop|endif))[a-z0-9'.'|_]+)'s%'}/si

前面包含else, endloopendif关键字的方括号将每个字符视为异常。这里它们被视为完整的字符串。