Sou*_*rav 31 php regex preg-replace
我想用一个Newline字符替换多个Newline字符,用一个空格替换多个空格.
我尝试过但preg_replace("/\n\n+/", "\n", $text);失败了!
我也在$ text上进行格式化.
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
Run Code Online (Sandbox Code Playgroud)
$ text是用户为BLOG拍摄的大文本,为了更好的格式化,我使用wordwrap.
Fra*_*nes 53
理论上,你定期快递确实有效,但问题是并非所有的操作系统和浏览器都只在字符串末尾发送\n.很多人也会发送\ r \n.
尝试:
编辑:我简化了这个:
preg_replace("/(\r?\n){2,}/", "\n\n", $text);
Run Code Online (Sandbox Code Playgroud)
编辑:并解决一些发送\ r的问题:
preg_replace("/[\r\n]{2,}/", "\n\n", $text);
Run Code Online (Sandbox Code Playgroud)
更新1:根据您的更新:
// 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);
Run Code Online (Sandbox Code Playgroud)
Arm*_*ier 35
使用\ R(代表任何行结束序列):
$str = preg_replace('#\R+#', '</p><p>', $str);
Run Code Online (Sandbox Code Playgroud)
在这里找到:http://forums.phpfreaks.com/topic/169162-solved-replacing-two-new-lines-with-paragraph-tags/
有关Escape序列的 PHP文档:
\ R(换行符:匹配\n,\ r和\ r \n)
这是答案,因为我理解这个问题:
// Normalize newlines
preg_replace('/(\r\n|\r|\n)+/', "\n", $text);
// Replace whitespace characters with a single space
preg_replace('/\s+/', ' ', $text);
Run Code Online (Sandbox Code Playgroud)
编辑
这是我用来将新行转换为HTML换行符和段落元素的实际函数:
/**
*
* @param string $string
* @return string
*/
function nl2html($text)
{
return '<p>' . preg_replace(array('/(\r\n\r\n|\r\r|\n\n)(\s+)?/', '/\r\n|\r|\n/'),
array('</p><p>', '<br/>'), $text) . '</p>';
}
Run Code Online (Sandbox Code Playgroud)