Trim multiple line breaks and multiple spaces off

2019-04-01 00:27发布

How can I trim multiple line breaks?

for instance,

$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
"

I tried with this answer but it does not work for the case above I think,

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

The answer I want to get is,

$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
    "

Only single line break is accepted.

Also I want to trim multiple white space at the same time, if I do this below, I can't save any line break!

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

How can I do both thing in line regex?

2条回答
地球回转人心会变
2楼-- · 2019-04-01 00:58

Your line breaks in this case are \r\n, not \n:

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

That says "every time 3 or more line breaks are found, replace them with 2 line breaks".

Spaces:

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

Demo: http://codepad.org/PmDE6cDm

查看更多
别忘想泡老子
3楼-- · 2019-04-01 00:59

Not sure if this is the best way, but I would use explode. For example:

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;
}

I hope this helps. Good luck!

查看更多
登录 后发表回答