【问题标题】:PHP preg_replace html comments with empty space [duplicate]PHP preg_replace 带有空格的html注释[重复]
【发布时间】:2011-01-30 17:47:19
【问题描述】:

我有一些这样的 php 代码:

$test = "<!--my comment goes here--> Hello World";

现在我想从字符串中删除整个 html 注释,我知道我需要使用 preg_replace,但现在确定要使用正则表达式。 有人可以帮忙吗? 谢谢

【问题讨论】:

    标签: php html regex comments preg-replace


    【解决方案1】:

    这应该会为你做的

    preg_replace("/<\!--.*?-->/s","",$html);
    

    【讨论】:

      【解决方案2】:
      <?php
      $test = "<!--my comment goes here--> Hello World";
      echo  preg_replace('/\<.*\> / ','',$test);
      ?>
      

      使用以下代码进行全局替换:

      <?php
      $test = "<!--my comment goes here--> Hello World <!--------welcome-->welcome";
      echo  preg_replace('/\<.*?\>/','',$test);
      ?>
      

      【讨论】:

        【解决方案3】:

        只有当你没有 2 个 cmets 的内容介于...之间时,这些才会起作用。

        <!--comment--> Im a goner <!--comment-->
        

        你需要...

        //preg_replace('/<!--[^>]*-->/', '', $html); // <- this is incorrect see ridgrunners comments below, you really need ...
        preg_replace('/<!--.*?-->/', '', $html);
        

        [^>] 匹配除 > 之外的任何内容,以免越过匹配的 > 寻找下一个。 我还没有测试过 phps 正则表达式,但它声称是 perl 正则表达式,默认情况下是“贪婪”的,并且会尽可能匹配。

        但由于您要匹配一个专门命名的占位符,您只需要整个字符串并使用 str_replace() 代替。

        str_replace('<!--my comment goes here-->', $comment, $html);
        

        而且,与其替换文件中的占位符,不如将其变成一个 php 文件并写出变量。

        :)

        【讨论】:

        • 不,&gt; 是允许的,并且在评论中完全有效。在这种情况下,.*?lazy-dot-star 实际上是更好的表达方式(并且不会像您推断的那样删除 "Im a goner" 文本),
        【解决方案4】:
        preg_replace('/<!--(.*)-->/Uis', '', $html)
        

        将删除 $html 字符串中包含的每个 html 注释。希望这会有所帮助!

        【讨论】:

        • 当我使用此代码时,它还会删除显示在 2 个单独的 HTML 注释块之间的内容。我认为 U 修饰符可能会使表达“贪婪”。我没有尝试调整它,而是使用ghostdog74's answer 中的表达式而不是 .*?代替 (.*) 并使用 /ms 代替 /Uis
        【解决方案5】:
        $str=<<<'EOF'
        <!--my comment goes here--> Hello World"
        blah  <!-- my another
        comment here --> blah2
        end
        EOF;
        
        $r="";
        $s=explode("-->",$str);
        foreach($s as $v){
          $m=strpos($v,'<!--');
          if($m!==FALSE){
           $r.=substr($v,1,$m);
          }
        }
        $r.=end($s);
        print $r."\n";
        

        输出

        $ php test.php
        Hello World"
        blah  < blah2
        end
        

        或者如果你必须 preg_replace,

        preg_replace("/<!--.*?-->/ms","",$str);
        

        【讨论】:

          【解决方案6】:

          试试

           preg_replace('~<!--.+?-->~s', '', $html);
          

          【讨论】:

          • 这是整个页面上唯一的好答案。我也添加了一个“m”修饰符。
          猜你喜欢
          • 2011-04-17
          • 2011-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多