【问题标题】:Replace multiple new lines with a single newline用一个换行符替换多个换行符
【发布时间】:2011-05-02 10:54:07
【问题描述】:

如何用一个换行符替换多个连续的换行符。最多可以有 20 个相邻的换行符。例如

James said hello\n\n\n\n Test\n Test two\n\n

最终应该是:

James said hello\n Test\n Test two\n

【问题讨论】:

    标签: php regex duplicates preg-replace newline


    【解决方案1】:

    试试这个:

    $str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
    $str = preg_replace("/\n+/", "\n", $str);
    print($str);
    

    【讨论】:

      【解决方案2】:

      改进 Marc B 的答案:

      $fixed_text  = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);
      

      它应该匹配一个初始换行符,然后是一组任意数量的空格中的至少一个,后跟一个换行符,并将其全部替换为一个换行符。

      【讨论】:

      • 使用 php 7 这会导致以下错误Warning: preg_replace(): Unknown modifier '+' in...
      • 修饰符 + 必须跟在一个字母或字符组之后。您使用的是整个正则表达式还是它的变体?
      • 我完全按照发布的方式使用了整个代码 sn-p。
      【解决方案3】:
      $fixed_text = preg_replace("\n+", "\n", $text_to_fix);
      

      应该这样做,假设连续的换行符是真正连续的,并且它们之间没有任何空格(制表符、空格、回车符等)。

      【讨论】:

        【解决方案4】:
        $str = 'James said hello\n\n\n\n Test\n Test two\n\n';
        echo preg_replace('{(\\\n)\1+}','$1',$str);
        

        【讨论】:

          【解决方案5】:

          在正则表达式中:

          • + 表示“前面的一个或多个表达式”
          • {2,} 表示“两个或多个前面的表达式”

          对于此问题中的要求,将单个 \n 替换为单个 \n 是没有意义的,因为该子字符串没有任何变化。换句话说,/\n+/ 只是做了多余的工作。

          使用两个或更多的范围量词更有意义。

          代码:(Demo)

          $string = "James said hello\n\n\n\n Test\n Test two\n\n";
          echo json_encode(
              preg_replace("/\n{2,}/", "\n", $string)
          );
          

          输出:

          "James said hello\n Test\n Test two\n"
          

          在其他情况下,将可能来自不同操作系统的换行符序列替换为\R 可能是有利的。此元字符匹配 \r\n\n。这是一个修改后的模式,它将用服务器指定的换行符序列替换两个或多个换行符序列:

          $string = "James\r\n said\n\r\n hello\r\n\r\n\r\n Test\n Test two\n\n";
          echo json_encode(
              preg_replace("/\R{2,}/", PHP_EOL, $string)
          );
          // "James\r\n said\n hello\n Test\n Test two\n"
          //       ^^^^----treated as one newline character sequence
          

          【讨论】:

            猜你喜欢
            • 2021-02-12
            • 2016-12-30
            • 2010-10-16
            • 1970-01-01
            • 1970-01-01
            • 2015-12-07
            • 1970-01-01
            • 1970-01-01
            • 2018-09-14
            相关资源
            最近更新 更多