preg_replace删除多个\ n

时间:2011-06-03 14:28:12

标签: php preg-replace line-endings

我一直在努力解决这个问题一个小时。我只需要一个可以学习的简单修复。 如何从下面的示例中删除多次出现的\ 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    \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

7 个答案:

答案 0 :(得分:3)

2种方式

while(strpos($string,"\n\n")!==false)
  str_replace("\n\n","\n",$string);

preg_replace("/\n+/","\n",$string);

答案 1 :(得分:2)

这应该有效:

<?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);

答案 2 :(得分:1)

如果这是真正的回车,您可以这样做以删除连续的回车:

preg_replace('/\n+/','\n',$yourString);

其他字符串'\ n'你可以做

preg_replace('/(\\n)+/','\n',$yourString);

最后,如果你想删除\ n之间的所有空格,你也可以

preg_replace('/\s*\n+/','\n',$yourString);

答案 3 :(得分:1)

尝试使用+迫使++匹配变得贪婪。

preg_replace('/\n++/',"\n",$yourString);

答案 4 :(得分:0)

奇怪,没有代码有效吗? 例如:

$barcodes = "5312353123123



5312353123123



5312353123123";
echo(     var_dump(   $barcodes     )     . '</br>' . "\n"  );
$barcodes = preg_replace('/\n+/', "\n", $barcodes);
exit(  var_dump(   $barcodes     )     . '</br>' . "\n"  );

输出:

string(55) "5312353123123 5312353123123 5312353123123"
string(55) "5312353123123 5312353123123 5312353123123"

这意味着该功能没有......没有?

答案 5 :(得分:0)

str_replace()手册页上的gotcha示例的另一种方法是:

// 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);

答案 6 :(得分:0)

尝试:

$newstr = preg_replace("/\r\n\r\n|\r\r|\n\n/", "..", $str);