【发布时间】:2011-05-02 10:54:07
【问题描述】:
如何用一个换行符替换多个连续的换行符。最多可以有 20 个相邻的换行符。例如
James said hello\n\n\n\n Test\n Test two\n\n
最终应该是:
James said hello\n Test\n Test two\n
【问题讨论】:
标签: php regex duplicates preg-replace newline
如何用一个换行符替换多个连续的换行符。最多可以有 20 个相邻的换行符。例如
James said hello\n\n\n\n Test\n Test two\n\n
最终应该是:
James said hello\n Test\n Test two\n
【问题讨论】:
标签: php regex duplicates preg-replace newline
试试这个:
$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
$str = preg_replace("/\n+/", "\n", $str);
print($str);
【讨论】:
改进 Marc B 的答案:
$fixed_text = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);
它应该匹配一个初始换行符,然后是一组任意数量的空格中的至少一个,后跟一个换行符,并将其全部替换为一个换行符。
【讨论】:
Warning: preg_replace(): Unknown modifier '+' in...
$fixed_text = preg_replace("\n+", "\n", $text_to_fix);
应该这样做,假设连续的换行符是真正连续的,并且它们之间没有任何空格(制表符、空格、回车符等)。
【讨论】:
$str = 'James said hello\n\n\n\n Test\n Test two\n\n';
echo preg_replace('{(\\\n)\1+}','$1',$str);
【讨论】:
在正则表达式中:
+ 表示“前面的一个或多个表达式”{2,} 表示“两个或多个前面的表达式”对于此问题中的要求,将单个 \n 替换为单个 \n 是没有意义的,因为该子字符串没有任何变化。换句话说,/\n+/ 只是做了多余的工作。
使用两个或更多的范围量词更有意义。
代码:(Demo)
$string = "James said hello\n\n\n\n Test\n Test two\n\n";
echo json_encode(
preg_replace("/\n{2,}/", "\n", $string)
);
输出:
"James said hello\n Test\n Test two\n"
在其他情况下,将可能来自不同操作系统的换行符序列替换为\R 可能是有利的。此元字符匹配 \r\n 或 \n。这是一个修改后的模式,它将用服务器指定的换行符序列替换两个或多个换行符序列:
$string = "James\r\n said\n\r\n hello\r\n\r\n\r\n Test\n Test two\n\n";
echo json_encode(
preg_replace("/\R{2,}/", PHP_EOL, $string)
);
// "James\r\n said\n hello\n Test\n Test two\n"
// ^^^^----treated as one newline character sequence
【讨论】: