preg_replace removes multiple "\n"s
How do I remove multiple occurrences of \n
from the sample below and replace with just one occurrence of \n
?
Basically I just want to remove multiple line breaks and replace them with just one line break.
\n\n\n\n\n\n\n\n \n\n \n\n\n\n\n\n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n \n \n \n \n \n \n\n \n\n \n\n \nEDITION: U.S.\n\n \nINTERNATIONAL\n\n \nMÉXICO\n\n \n\n \nSet edition preference\n\n \n\n \n\n \n\n \nSign up\n\n \nLog in\n\n \n\n \n\n \n\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n \n\n \n\n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n \nHome\n\n \nVideo\n\n \nNewsPulse\n\n \nU.S.\n\n \nWorld\n\n \nPolitics\n\n \nJustice\n\n \nEntertainment\n\n \nTech\n\n \nHealth\n\n \nLiving\n\n \nTravel\n\n \nOpinion\n\n \niReport\n\n \nMoney\n\n \nSports\n\n \n\n \n\n\n\n\n\n \n\n\n\n\n\n\n\n \n\n\n\n \n\n\n\n\n\n\n \n\nupdated 10:02 a.m.EDT, Fri June 3, 2011\n\n\n\n\n\n \n\n\n\n\n\nDr. Jack Kevorkian dead at 83\n\n\n\n\n\n\nThe Michigan pathologist who put assisted suicide on the world\'s medical ethics stage, apparently died of 开发者_开发技巧a blood clot, according to his attorney. FULL STORY
Two ways
while(strpos($string, "\n\n") !== false)
str_replace("\n\n", "\n", $string);
And
preg_replace("/\n+/", "\n", $string);
This should work:
<?php
$string = "\n\n\n\n Text \n\n Text \n\n\n\n\n Text \n\n\n";
echo preg_replace("#[\n]+#", "\n", $string);
If this is a real carriage return you can do this to remove successive carriage returns:
preg_replace('/\n+/', '\n', $yourString);
Else for the string '\n' you can do:
preg_replace('/(\\n)+/', '\n', $yourString);
Finally, if you want to remove all spaces in between your \n too you can do"
preg_replace('/\s*\n+/', '\n', $yourString);
Try forcing the +
match to be greedy, by using ++
instead.
preg_replace('/\n++/', "\n", $yourString);
Strange, none of the code works? Example:
$barcodes = "5312353123123
5312353123123
5312353123123";
echo( var_dump( $barcodes ) . '</br>' . "\n" );
$barcodes = preg_replace('/\n+/', "\n", $barcodes);
exit( var_dump( $barcodes ) . '</br>' . "\n" );
Output:
string(55) "5312353123123 5312353123123 5312353123123"
string(55) "5312353123123 5312353123123 5312353123123"
That means the function does... nothing?
Another way from the gotcha's examples on the man page for str_replace() is:
// Order of replacement
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);
Try:
$newstr = preg_replace("/\r\n\r\n|\r\r|\n\n/", "..", $str);
精彩评论