【问题标题】:Trim multiple line breaks and multiple spaces off a string?从字符串中修剪多个换行符和多个空格?
【发布时间】:2011-11-11 19:21:08
【问题描述】:

如何修剪多个换行符?

例如,

$text ="similique sunt in culpa qui officia


deserunt mollitia animi, id est laborum et dolorum fuga. 



Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore
"

我试过这个answer,但我认为它不适用于上述情况,

$text = preg_replace("/\n+/","\n",trim($text));

我想得到的答案是,

$text ="similique sunt in culpa qui officia

    deserunt mollitia animi, id est laborum et dolorum fuga. 

    Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore
    "

只接受单行换行

另外我想同时修剪多个空白,如果我在下面这样做,我无法保存任何换行符!

$text = preg_replace('/\s\s+/', ' ', trim($text));

如何在正则表达式中同时做这两件事?

【问题讨论】:

    标签: php regex preg-replace trim


    【解决方案1】:

    在这种情况下,您的换行符是\r\n,而不是\n

    $text = preg_replace("/(\r\n){3,}/","\r\n\r\n",trim($text));
    

    意思是“每次找到 3 个或更多换行符时,用 2 个换行符替换它们”。

    空格:

    $text = preg_replace("/ +/", " ", $text);
    //If you want to get rid of the extra space at the start of the line:
    $text = preg_replace("/^ +/", "", $text);
    

    演示:http://codepad.org/PmDE6cDm

    【讨论】:

    • 如果我这样做,它会修剪掉所有的换行符preg_replace("/(\s){2,}/"," ",trim($text))
    • 答案已更新。 \s 用于所有空格,包括换行符。对于空格,只需使用实际的空格字符 当字符串中包含转义字符(如\n\s)时,请务必使用双引号
    【解决方案2】:

    不确定这是否是最好的方法,但我会使用爆炸。例如:

    function remove_extra_lines($text)
    {
      $text1 = explode("\n", $text); //$text1 will be an array
      $textfinal = "";
      for ($i=0, count($text1), $i++) {
        if ($text1[$i]!="") {
          if ($textfinal == "") {
            $textfinal .= "\n";  //adds 1 new line between each original line
          }
          $textfinal .= trim($text1[$i]);
        }
      }
      return $textfinal;
    }
    

    我希望这会有所帮助。祝你好运!

    【讨论】:

    • 我知道...这就是为什么我在顶部添加免责声明,说我不确定这是否是最好的方法。我想我需要考虑一些更复杂的函数,比如 preg_replace。 :O)
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多