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);
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
只是为了变化:
array_diff(explode('/', '1/2//3/'), array(''))
Run Code Online (Sandbox Code Playgroud)
这也有效,但与preg_split不同,它确实搞乱了数组索引.有些人可能比声明回调函数使用array_filter更好.
function not_empty_string($s) {
return $s !== "";
}
array_filter(explode('/', '1/2//3/'), 'not_empty_string');
Run Code Online (Sandbox Code Playgroud)