【问题标题】:PHP very odd outcomePHP 很奇怪的结果
【发布时间】:2011-09-09 01:09:52
【问题描述】:

如果我这样做:

$comments = str_replace( "\n\n", "\n", $comments );

还有这个:

$comments = explode( "\n", $comments );

那么循环下去,这怎么可能……

if( strlen( $comments[ $i ] ) == 0 )

...可能是真的???

实际上并没有更多的上下文,它非常简单,而且我是一名长期的 PHP 开发人员,这真的让我很难过。

附:我也尝试过类似...

$comments = str_replace( "\n\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );
$comments = str_replace( "\n\n", "\n", $comments );

...连续,我仍然遇到同样的问题。

【问题讨论】:

  • 你的 $cmets 数组的 var_dump() 告诉你关于你的数组的什么?我通常也使用 empty() 而不是 strlen()==0
  • 1.检查是否有 BR 而不是 \n; 2.如果是,请先更换它;如果 \n\n 则退出 \r\n 组合,因此请先尝试替换它; 4.您必须使用 REGEX 将连续的 \n\n\n 替换为唯一的 \n
  • 替换 \r\n 也不起作用,我只是尝试了 empty() 而不是 strlen() 但这不起作用,有问题!
  • 改用preg_replace$comments = preg_replace("~\n{2,}~", "\n", $comments);

标签: php explode


【解决方案1】:

其他几个答案指出了两个以上相邻换行符的可能性。

将空字符串作为explode 输出的一部分的另一种简单方法是在末尾带有换行符的输入字符串:

"hey\n"

(如果是"\n\n" 也会发生这种情况)

通过您的代码运行它会为您提供以下数组:

array(2) {
  [0]=>
  string(3) "hey"
  [1]=>
  string(0) ""
}

【讨论】:

  • 宾果游戏!该死的,谢谢你,今天有很多字符串操作,我应该明白这一点;)
【解决方案2】:

如果 $cmets 包含 \n\n\n 则替换后,它将是 \n\n 导致爆炸时为空元素。

【讨论】:

  • 只需调用你的 str_replace 两次,它就会去掉奇数的\n。
  • 还有\n\n\n\n\n\n\n\n\n等的剩菜
【解决方案3】:

确保 $cmets 不是空字符串

【讨论】:

  • 这个“会”最有意义,因为我的 for 循环在另一个循环中,但我刚刚检查过 $cmets 总是至少有几行文本。
【解决方案4】:

试试这个

$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 )

【讨论】:

  • 字符串中没有 html,抱歉我忘了说。
【解决方案5】:

我认为大多数 Regex/String 函数只通过一次。因此类似于:

str_replace("\n\n", "\n", "\n\n\n\n")

会给你

"\n\n"

因为替换只遍历字符串一次,而不是重复直到不再找到被替换者。如果您想折叠多个换行符,我认为您可以使用:

preg_replace("[\\n]+", "\n", "\n\n\n\n")

如果我正确地记得我的 PHP 正则表达式。这将用单个“\n”替换任何连续的1个或多个“\n”集

【讨论】:

    【解决方案6】:

    安全地摆脱任何多个换行符。用修剪去除前导和尾随换行符。

    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));
    

    【讨论】:

    • 刚试过这个,没有骰子,它仍然有一个空的索引。
    • 刚刚尝试了一个新字符串,得到了一个没有被 str_replace 捕获的字符串。使用 preg_replace 更新帖子。
    【解决方案7】:

    我认为以下应该解决这两个问题:

    <?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) );
    ?>
    

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 2013-11-03
      • 2018-03-11
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      相关资源
      最近更新 更多