【问题标题】:how to delete carriage returns in html using php?如何使用php删除html中的回车?
【发布时间】:2009-06-03 15:58:51
【问题描述】:

我正在使用一个 javascript 函数,该函数接收一些使用 php 包含的 html 代码。 它不是 php 字符串中的 html,而是带有 .php 扩展名的 html 文件。

由于 html 代码作为参数发送给 js 函数,因此它不能包含回车符。问题是在一行中写大块的 html 很糟糕,我希望有一个函数只在发送内容之前擦除回车。

这样的功能有来源吗?

谢谢!

【问题讨论】:

    标签: php javascript html carriage-return


    【解决方案1】:

    简单

    echo str_replace(array("\r\n", "\r", "\n"), null, $htmlCode);
    

    【讨论】:

      【解决方案2】:

      当您说“在 PHP 文件中”时,我假设您的意思是您正在 include()ing 一个看起来像这样的文件:

      <html>
        <head><title>Foo</title></head>
        <body>
          <?php do_stuff(); ?>
        </body>
      </html>
      

      如果是这种情况,您要查找的内容称为Output Control,它允许您在准备好之前阻止发送数据,或者将其捕获到字符串中以进行额外处理。要从包含的文件中删除回车,您可以这样做:

      <?php
      
      ob_start();                       // start buffering output
      include("foo.php");               // include your file
      $foo = ob_get_contents();         // get a copy of the buffer's contents
      ob_clean_end();                   // discard the buffer and turn off buffering
      echo str_replace("\r", "", $foo); // print output w/o carriage returns
      

      如果您还想删除换行符,请将最后一行更改为:

      echo str_replace(array("\n", "\r"), "", $foo);
      

      【讨论】:

        【解决方案3】:

        “用 PHP 构建”我假设您的意思是您正在构建一个包含相关 HTML 的字符串。

        如果是这种情况,那么简单的问题就是不要将回车符作为字符串的一部分。

        也就是说,不要这样做:

        foo =  "  this is my string
                 and I have it on two lines"; 
        

        而是这样做

        foo = "" .
              " this is my string" .
              " and it's on one line ";
        

        当然,您可以使用 string.replace 函数,但通过 concats 构建意味着您可以跳过该步骤。

        【讨论】:

        • 我认为你的意思是 .= 而不是 += 。
        • aye.. 我责怪从现在到最后一次写任何 php 的 6 年
        【解决方案4】:

        这是一个简单的string substitution

        【讨论】:

          【解决方案5】:

          考虑为此使用XML writer,如果这是您的 javascript 解析的内容。这样结果将始终有效,并且代码应该变得更清晰。

          【讨论】:

          • 在大多数情况下,磁盘 I/O 是主要瓶颈。我会这样做并缓存结果。
          猜你喜欢
          • 2014-01-15
          • 2010-09-22
          • 1970-01-01
          • 2012-02-19
          • 2019-11-29
          • 2016-09-06
          • 2014-09-20
          • 1970-01-01
          • 2012-10-05
          相关资源
          最近更新 更多