【问题标题】:Remove empty array elements from exploded string [duplicate]从分解的字符串中删除空数组元素[重复]
【发布时间】:2012-07-10 06:40:50
【问题描述】:

可能重复:
Remove empty array elements

我想从数组中删除空元素。我有一个由explode() 设置为数组的字符串。然后我使用array_filter() 删除空元素。但这不起作用。请参阅下面的代码:

$location = "http://www.bespike.com/Packages.gz";
$handle = fopen($location, "rb");
$source_code = stream_get_contents($handle);
$source_code = gzdecode($source_code);
$source_code = str_replace("\n", ":ben:", $source_code);
$list = explode(":ben:", $source_code);
print_r($list);

但它不起作用,$list 仍然有空元素。我也尝试过使用empty() 函数,但结果是一样的。

【问题讨论】:

标签: php arrays explode


【解决方案1】:

如果文件有\r\n 作为回车符,就像那个那样,用\n 分割会得到一个显示为空但不是的元素——它包含@987654323 @。

$source_code = gzdecode($source_code);
$list = array_filter(explode("\r\n", $source_code));
print_r($list);

您也可以尝试使用现有代码,替换“\r\n”而不是“\n”(您仍然需要在某个地方使用 array_filter)。

一个可能更慢但更灵活的选项使用preg_split 和特殊的正则表达式元字符\R 匹配任何换行符,包括Unix和Windows:

$source_code = gzdecode($source_code);
$list = array_filter(preg_split('#\\R#', $source_code));
print_r($list);

【讨论】:

  • 谢谢你,工作完美谢谢:)
  • @downvoter:有问题吗?随意添加评论,甚至提出问题 [请记住明确说明问题所在 - 我只是假设上述内容对您不起作用;这对我来说没什么可做的]。
【解决方案2】:

这是你需要的:

$list = array_filter($list, 'removeEmptyElements');

function removeEmptyElements($var)
{
  return trim($var) != "" ? $var : null;
}

如果没有提供回调,所有等于 FALSE 的输入条目都将被删除。但是在您的情况下,您有一个长度为 1 的空字符串,这不是 FALSE。这就是为什么我们需要提供回调

【讨论】:

    【解决方案3】:
    $arr = array('one', '', 'two');
    $arr = array_filter($arr, 'strlen');
    

    请注意,这不会重置键。以上将为您留下一个包含两个键的数组 - 02。如果您的数组是索引的而不是关联的,您可以通过

    $arr = array_values($arr);
    

    密钥现在将是 01

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2022-11-16
      • 2017-09-12
      • 2019-03-14
      • 2015-06-23
      相关资源
      最近更新 更多