dongxi8993 2016-08-25 11:40
浏览 42
已采纳

PHP preg_replace()与空格和新行不匹配:为什么?

I'm trying to code a script that removes comments from HTML, except those that begin with [ or !. For example, the comments below should be removed:

<!-- one line comment -->

<!-- multiple line comment -->

The following should not be removed:

<!-- ! one line comment -->

<!--! one line comment -->

<!--! multiple line comment -->

<!-- ! multiple line comment -->

<!-- !multiple line comment -->

<!--[if lt IE 9]>

I'm trying to run the following:

$html = preg_replace('/<!--[\s ]*[^![].*-->/Uis', '', $html);

But it doesn't match the first class of characters (any quantity of spaces and new lines). For example, <!-- !test --> is removed from HTML, while <!--!test --> is not.

What's wrong?

  • 写回答

2条回答 默认 最新

  • douzhang8840 2016-08-25 11:56
    关注

    Add + after <!--[\s ]* in your pattern :

    $pattern = '<!--[\s
    ]*+[^![].*-->';
    
    $string = '<!-- one line comment -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!--
    multiple line comment
    -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!-- ! one line comment -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!--! one line comment -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!--!
    multiple line comment
    -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!-- !
    multiple line comment
    -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!--
    !multiple line comment
    -->';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    
    $string = '<!--[if lt IE 9]>';
    var_dump(preg_replace('/' . $pattern . '/Uis', '', $string));
    

    Output :

    string '' (length=0)
    
    string '' (length=0)
    
    string '<!-- ! one line comment -->' (length=27)
    
    string '<!--! one line comment -->' (length=26)
    
    string '<!--!
    
    multiple line comment
    
    -->' (length=33)
    
    string '<!-- !
    
    multiple line comment
    
    -->' (length=34)
    
    string '<!--
    
    !multiple line comment
    
    -->' (length=33)
    
    string '<!--[if lt IE 9]>' (length=17)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 论文AlphaTensor复现(有偿)
  • ¥15 (有偿)在ANSYS中 .anf文件
  • ¥45 关于#芯片#的问题:组合逻辑电路设计
  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通