如果我这样做:
$comments = str_replace( "\n\n", "\n", $comments );
而且:
$comments = explode( "\n", $comments );
然后在循环中,这怎么可能......
if( strlen( $comments[ $i ] ) == 0 )
......可能是真的???
实际上没有更多的上下文,它非常直接,我是一个很长时间的PHP开发人员,这真的让我感到难过。
P.S。我也试过像......
$comments = str_replace( "\n\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
......接连,我仍然遇到同样的问题。
答案 0 :(得分:1)
其他几个答案指出了两个以上相邻换行符的可能性。
将空字符串作为explode
输出的一部分的另一种简单方法是输入字符串,其末尾有换行符:
"hey\n"
(如果"\n\n"
那里也会发生这种情况)
通过代码运行它会为您提供以下数组:
array(2) {
[0]=>
string(3) "hey"
[1]=>
string(0) ""
}
答案 1 :(得分:0)
如果$ comments包含\ n \ n \ n然后在替换后,它将是\ n \ n,导致爆炸时出现空元素。
答案 2 :(得分:0)
确保$ comments不是空字符串
答案 3 :(得分:0)
试试这个
$comments = str_replace( "<br>", "\r\n", $comments ); //incase if there is br , change to \n
$comments = trim($comments);
$comments = preg_replace("/[\r\n]+/", "\n", $comments);
$comments = str_replace( "\n\n", "\n", $comments );
$comments = trim($comments);
$comments = explode( "\n", $comments );
然后
if( strlen( $comments[ $i ] ) == 0 )
答案 4 :(得分:0)
我认为大多数Regex / String函数只进行一次传递。因此类似于:
str_replace("\n\n", "\n", "\n\n\n\n")
会给你
"\n\n"
因为替换只通过字符串一次,而不是重复,直到找不到替换。如果你想折叠多个换行符,我想你可以使用:
preg_replace("[\\n]+", "\n", "\n\n\n\n")
如果我正确记住我的PHP正则表达式。这将用一个“\ n”
替换任何一个或多个“\ n”的连续集合答案 5 :(得分:0)
安全地删除任何多个换行符。使用修剪取出前导和尾随换行符。
while (strpos($comments, "\n\n") !== false)
$comments = str_replace( "\n\n", "\n", trim($comments) );
更新:使用preg_replace,可以更好地清理 - 你可以删除任何上面的空行。
$comments = preg_replace("/\s*\n\n\s*/", "\n", trim($comments));
答案 6 :(得分:0)
我认为以下两个问题应该解决:
<?php
$comments = "\nHello\n\n\nWorld\n\n\n\n\n";
//replace two+ \n togheter for one \n
$comments = preg_replace("/\n{2,}/", "\n", $comments);
//remove if there's one at the beginning or end
$comments = preg_replace("/(^\n|\n$)/", "", $comments);
//should only have two elements
print_r( explode("\n",$comments) );
?>