在字符类中我可以匹配完整单词吗?
使用此代码,正则表达式会删除 {else}
标记,因此是否可以将 else
添加到字符类内部作为单词,而不是作为4个字母?
$section = "
{if {money} == 'yes'}
Sweet!
{else}
Too bad...
{/if}
";
echo preg_replace("/\{[^ \/]+\}/iU", "''", $section);
我认为这可能有效(但事实并非如此):
echo preg_replace("/\{[^ (else)\/]+\}/iU", "''", $section);
预期输出:
{if '' == 'yes'}
Sweet!
{else}
Too bad...
{/if}
最佳答案
不。您绝对不能将单词放置在字符类[]
中。
但是您可以在此处使用Negative Lookahead。
$section = <<<DATA
{if {money} == 'yes'}
Sweet!
{else}
Too bad...
{/if}
DATA;
$section = preg_replace('~\{(?!else|/)\S+\}~i', "''", $section);
echo $section;
正则表达式:
\{ '{'
(?! look ahead to see if there is not:
else 'else'
| OR
/ '/'
) end of look-ahead
\S+ non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)
\} '}'
关于php - 字符类中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752879/