Reputation: 57196
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?
Upvotes: 3
Views: 6707
Reputation: 26627
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
Upvotes: 7
Reputation: 5734
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!
Upvotes: 0