3

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?

Community
  • 1
  • 1
Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

7

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

bcoughlan
  • 25,987
  • 18
  • 90
  • 141
  • 1
    if I do this, it will trim off all the line breaks `preg_replace("/(\s){2,}/"," ",trim($text))` – Run Sep 07 '11 at 03:23
  • Answer updated. `\s` is for all whitespace, including newlines. For spaces just use an actual space character Also be sure to use double quotes when strings have escaped characters (like `\n` or `\s`) in them – bcoughlan Sep 07 '11 at 03:28
0

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!

jdias
  • 5,572
  • 4
  • 22
  • 25
  • I know... this is why I included the disclaimer at the top saying that I am not sure if this was the best way. I guess I need to get my mind around the more sophisticated functions like preg_replace. :O) – jdias Sep 07 '11 at 03:15