爆炸不会返回空字符串?

Gle*_*oss 31 php

PHP的explode函数返回在一些提供的子字符串上拆分的字符串数组.它会像这样返回空字符串:

var_dump(explode('/', '1/2//3/'));
array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "3"
  [4]=>
  string(0) ""
}
Run Code Online (Sandbox Code Playgroud)

是否有一些不同的函数或选项或任何会返回空字符串之外的所有内容?

var_dump(different_explode('/', '1/2//3/'));
array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
Run Code Online (Sandbox Code Playgroud)

cee*_*yoz 59

试试preg_split.

$exploded = preg_split('@/@', '1/2//3/', NULL, PREG_SPLIT_NO_EMPTY);

  • preg_split将返回一个带有顺序数组索引的数组(即0,1,2,3).使用array_filter的一些其他建议将返回非顺序数组索引,因为一些元素被过滤掉,而你会留下像0,1,3,7这样的数组索引. (5认同)
  • @RafikBari 正则表达式模式的第一个字符是它的分隔符。请参阅 http://php.net/manual/en/regexp.reference.delimiters.php。`/` 通常被使用,但我在这里使用了 `@`,因为 `/` 在我们的字符串中。 (2认同)

Dav*_*ory 20

array_filter将删除空白字段,这是一个没有过滤器的示例:

print_r(explode('/', '1/2//3/'))
Run Code Online (Sandbox Code Playgroud)

打印:

Array
(
    [0] => 1
    [1] => 2
    [2] =>
    [3] => 3
    [4] =>
)
Run Code Online (Sandbox Code Playgroud)

使用过滤器:

php> print_r(array_filter(explode('/', '1/2//3/')))
Run Code Online (Sandbox Code Playgroud)

打印:

Array
(
    [0] => 1
    [1] => 2
    [3] => 3
)
Run Code Online (Sandbox Code Playgroud)

您将获得解析为"false"的所有值过滤掉.

http://uk.php.net/manual/en/function.array-filter.php

  • 这也会删除'0',因为它在布尔上下文中是假的.所以它可能不是你想要的! (7认同)

Gle*_*oss 7

只是为了变化:

array_diff(explode('/', '1/2//3/'), array(''))
Run Code Online (Sandbox Code Playgroud)

这也有效,但与preg_split不同,它确实搞乱了数组索引.有些人可能比声明回调函数使用array_filter更好.


Jam*_*ett 5

function not_empty_string($s) {
  return $s !== "";
}

array_filter(explode('/', '1/2//3/'), 'not_empty_string');
Run Code Online (Sandbox Code Playgroud)