我想用一个空格替换一个换行符多个换行符和多个空格。
我试图preg_replace("/\n\n+/", "\n", $text);
和失败!
我还做了格式化的文本$这项工作。
$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);
$文本是从用户采取BLOG一个大的文本,并为更好的格式我用换行。
从理论上讲,你的正则表达式的工作,但问题是,并不是所有的操作系统和浏览器只发送\ 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处理strip_tags的功能,有一些问题,如:具有断行后,然后出现一些空格的新线,然后一个新的断行连续出现...等。没有任何规则:(。
这是我对于处理用strip_tags解决方案
多个空格替换一个,多个换行符单换行符
function cleanHtml($html)
{
// Clean code into script tags
$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
// Clean code into style tags
$html = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', '', $html );
// Strip HTML
$string = trim(strip_tags($html));
// Replace multiple spaces on each line (keep linebreaks) with single space
$string = preg_replace("/[[:blank:]]+/", " ", $string); // (*)
// Replace multiple spaces of all positions (deal with linebreaks) with single linebreak
$string = preg_replace('/\s{2,}/', "\n", $string); // (**)
return $string;
}
关键字是(*)和(**)。
使用\ R(其表示结束序列中的任何行):
$str = preg_replace('#\R+#', '</p><p>', $str);
有人在这里找到:Replacing two new lines with paragraph tags
约Escape sequences 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);
这是我用来转换新的生产线,以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>';
}
你需要多修改,以匹配多行:
preg_replace("/PATTERN/m", "REPLACE", $text);
另外,在您的例子中,你似乎恰好与2更换2+换行,这是不是你的问题表明什么。
我尝试了所有的上面,但它并没有为我工作。然后,我创建了一些很长的路来解决这个问题?
之前:
echo nl2br($text);
后:
$tempData = nl2br($text);
$tempData = explode("<br />",$tempData);
foreach ($tempData as $val) {
if(trim($val) != '')
{
echo $val."<br />";
}
}
而且它为我工作。我写到这里,因为,如果有人来这里找到答案像我一样。
我建议是这样的:
preg_replace("/(\R){2,}/", "$1", $str);
这将需要的所有的Unicode换行符护理。
如果你只是想用一个标签来替代多个标签,使用下面的代码。
preg_replace("/\s{2,}/", "\t", $string);
尝试这个:
preg_replace("/[\r\n]*/", "\r\n", $text);
更换头部和字符串或文档的结尾!
preg_replace('/(^[^a-zA-Z]+)|([^a-zA-Z]+$)/','',$match);