【问题标题】:php preg_replace remove <br> with style attrphp preg_replace 删除 <br> 样式 attr
【发布时间】:2011-02-25 16:52:31
【问题描述】:
<br style="clear: both">

以下正则表达式对我不起作用,我做错了什么?

return preg_replace('#<br[^>]+style="clear:both"[^/>]#is', '',  $output);

谢谢。

【问题讨论】:

  • 不起作用,因为“clear:”和“both”之间的空格不匹配

标签: php regex html-parsing


【解决方案1】:

如果你的字符串总是:

<br style="clear: both">

您可以改用str_replace

return str_replace('<br style="clear: both">', '',  $output);

Beware that you shouldn't use regex for html manipulation.

改用一些解析器 HTML。

【讨论】:

    【解决方案2】:

    您可以转义诸如 =:> 等字符。 像这样的:

    <?php    
    return preg_replace('#\<br[^>]+style\=\"clear\:both\"[^/>]#is', '',  $output);
    ?>
    

    更多更好的例子:

    <?php
    return preg_replace('#\<br*.?\>#is', '',  $output);
    ?>
    

    【讨论】:

    • 不,这些字符没有特殊含义,因此转义它们是没有意义的。另外,第二个建议中的*.? 应该是.*?
    【解决方案3】:

    试试这个:

    #<br *style="clear: *both"/?>#is
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多