PHP 非常奇怪的结果
如果我这样做:
$comments = str_replace( "\n\n", "\n", $comments );
然后这样:
$comments = explode( "\n", $comments );
然后在一个循环中,这怎么可能......
if( strlen( $comments[ $i ] ) == 0 )
可能是真的???
确实没有更多的上下文,它非常简单,而且我是一名长期的 PHP 开发人员,这确实难倒了我。
PS我也
$comments = str_replace( "\n\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
连续尝试过类似的方法,但仍然遇到同样的问题。
If I do this:
$comments = str_replace( "\n\n", "\n", $comments );
And this:
$comments = explode( "\n", $comments );
Then in a loop, how could this...
if( strlen( $comments[ $i ] ) == 0 )
...possibly be true???
There's not really any more context to it, it's pretty straight forward and I'm a long time PHP developer, this is really stumping me.
P.S. I've also tried something like...
$comments = str_replace( "\n\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
...in succession and I still get the same issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
其他几个答案指出了两个以上相邻换行符的可能性。
将空字符串作为
explode
输出的一部分的另一种简单方法是输入字符串末尾带有换行符:(如果它是
"\n\n" ,也会发生这种情况
)通过代码运行它会得到以下数组:
Several other answers have pointed out the possibility of more than two adjacent line breaks.
Another easy way for an empty string to be part of the
explode
output would be an input string with a line break at the end:(this would also happen if it's
"\n\n"
there)Running that through your code gives you the following array:
如果 $comments 包含 \n\n\n 则替换后,它将 \n\n 导致爆炸时为空元素。
If $comments contains \n\n\n then after replacement, it will be \n\n resulting in an empty element at explode.
确保 $comments 不是空字符串
Make sure $comments isn't an empty string
试试这个
然后
Try this
and then
我认为大多数正则表达式/字符串函数只进行一次传递。因此,类似:
会给你,
因为替换只遍历字符串一次,并且不会重复,直到不再找到替换。如果你想折叠多个换行符,我想你可以使用:
如果我正确地记得我的 PHP 正则表达式。这会将任何连续的 1 个或多个“\n”集合替换为单个“\n”
I think most Regex/String functions only make a single pass. Hence something like:
will give you
because the replacement only goes through the string once, and not repeatedly until the replacee is no longer found. If you want to collapse multiple newlines, i think you could use:
if i remember my PHP regexes correctly. That would replace any contiguous set of 1 or more "\n"s with a single "\n"
安全地删除任何多个换行符。用修剪去除前导和尾随换行符。
更新:使用 preg_replace,可以获得更好的清理效果 - 您可以删除上面空行中留下的任何空行。
Safely get rid of any multiple of newlines. Takes out leading and trailing newlines with the trim.
Update: using preg_replace, it's possible to get a better clean - you can remove any empty lines which would be left in with the one above.
我认为以下应该可以解释这两个问题:
I think the following should account for both issues: