字符类中的单词

Get*_*awn 2 php regex preg-replace

在角色课中,我可以匹配完整的单词吗?

使用此代码,正则表达式将删除{else}标记,因此是否可以将else字符类内部添加为单词,而不是4个字母?

$section = "
{if {money} == 'yes'}
   Sweet!
{else}
    Too bad...
{/if}
";

echo preg_replace("/\{[^ \/]+\}/iU", "''", $section);
Run Code Online (Sandbox Code Playgroud)

我认为这可能有效(但事实并非如此):

echo preg_replace("/\{[^ (else)\/]+\}/iU", "''", $section);
Run Code Online (Sandbox Code Playgroud)

预期产量:

{if '' == 'yes'}
   Sweet!
{else}
    Too bad...
{/if}
Run Code Online (Sandbox Code Playgroud)

hwn*_*wnd 5

.你绝对不能在单词类中放置单词[].

但是你可以在这里使用否定前瞻.

$section = <<<DATA
{if {money} == 'yes'}
   Sweet!
{else}
    Too bad...
{/if}
DATA;

$section = preg_replace('~\{(?!else|/)\S+\}~i', "''", $section);
echo $section;
Run Code Online (Sandbox Code Playgroud)

看到 Live demo

正则表达式:

\{            '{'
 (?!          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)
\}            '}'
Run Code Online (Sandbox Code Playgroud)