【问题标题】:preg_replace in php to remove tags that are multiple time in sting [duplicate]php中的preg_replace删除多次刺痛的标签[重复]
【发布时间】:2019-09-29 12:45:10
【问题描述】:

我有一个问题,我需要清除变量中的所有字体标签:

$old = '[FONT=arial]Dit is een tekst [FONT=Courier New]nonononon';
$new = preg_replace('/\[FONT=(.*)\](.*)/', "$2", $old);
echo "\nold   = $old\nnew = $new\n";

但是这样做的结果是:

old = [FONT=arial]Dit is een tekst [FONT=Courier New]nonononon
new = nonononon

我想要的结果是:

old = [FONT=arial]Dit is een tekst[FONT=Courier New]nonononon
new = Dit is een tekst nonononon

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你需要让你的正则表达式变得懒惰,使用(.*?)

    参考:- Regex lazy qunatifiers

    \[FONT=(.*?)\](.*?)
    

    Regex demo


    $re = '/\[FONT=(.*?)\](.*?)/m';
    $str = '[FONT=arial]Dit is een tekst [FONT=Courier New]nonononon';
    $subst = '$2';
    
    $result = preg_replace($re, $subst, $str);
    

    输出

    Dit is een tekst nonononon
    

    【讨论】:

      【解决方案2】:

      您不需要任何捕获组。您可以使用此正则表达式来匹配和删除您不想要的内容:

      $old = '[FONT=arial]Dit is een tekst [FONT=Courier New]nonononon';
      $new = preg_replace('/\[FONT=[^]]*]/', '', $old);
      echo "$new\n";
      

      Dit is een tekst nonononon
      

      [^]] 是一个否定字符类,它将匹配任何不是] 的字符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多