<分区>
我想用一个换行符替换多个换行符,用一个空格替换多个空格。
我尝试了 preg_replace("/\n\n+/", "\n", $text);
但失败了!
我还在 $text 上做这项工作以进行格式化。
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$text 是为 BLOG 从用户那里获取的大文本,为了更好的格式,我使用了 wordwrap。
标签 php regex preg-replace
<分区>
我想用一个换行符替换多个换行符,用一个空格替换多个空格。
我尝试了 preg_replace("/\n\n+/", "\n", $text);
但失败了!
我还在 $text 上做这项工作以进行格式化。
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$text 是为 BLOG 从用户那里获取的大文本,为了更好的格式,我使用了 wordwrap。
最佳答案
理论上,您的正则表达式确实有效,但问题是并非所有操作系统和浏览器都只在字符串末尾发送\n。许多人还会发送一个\r。
试试:
我已经简化了这个:
preg_replace("/(\r?\n){2,}/", "\n\n", $text);
并且解决一些只发送\r的问题:
preg_replace("/[\r\n]{2,}/", "\n\n", $text);
根据您的更新:
// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = wordwrap($text,120, '<br/>', true);
$text = nl2br($text);
关于php - 替换多个换行符、制表符和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6360566/