【问题标题】:PHP Regular Expression {{ }}PHP 正则表达式 {{ }}
【发布时间】:2015-07-10 02:27:53
【问题描述】:

我很难为 preg_match 编写 PHP 正则表达式。基本上我需要匹配以下模式:

{{anything}}
{{{anything}}}

但这是最简单的部分。如果字符串只包含这个,我想用“”(空字符串)替换这样的表达式,但如果字符串包含其他东西,我需要保留,所以下面的字符串将变得有效:

this is about {{anything}}
{{{anything}}} anywhere

非常感谢您的帮助:)。

【问题讨论】:

  • 看起来换行符不起作用。请注意 {{ }} 周围有换行符
  • 当你说“如果字符串只包含这个”时,首先检查字符串是否包含正在寻找的任何 'this' 然后如果是这种情况,请使用 preg_replace

标签: php regex


【解决方案1】:

只需使用锚点。

preg_replace('~^\{+[^{}]*\}+$\n?~m', '', $str);

DEMO

【讨论】:

  • 需要以\}+结尾
【解决方案2】:

你也可以使用T-Regx

pattern('\{+[^{}]*\}+')->replace()->all()->callback(function (Match $m) {
    if ($m->text() === 'anything') {
        return '';
    }
    return $m->text();
});

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2013-05-30
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多