使用 PHP 分解字符串时如何删除所有空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3432183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove all empty values when I explode a string using PHP?
提问by snag
I was wondering how can I remove all empty values when I explode a string using PHP for example, lets say a user enters ",jay,john,,,bill,glenn,,,"
?
我想知道当我使用 PHP 分解字符串时如何删除所有空值,例如用户输入",jay,john,,,bill,glenn,,,"
?
Thanks in advance for the help.
在此先感谢您的帮助。
Here is part of the code that explodes user submitted values.
这是分解用户提交值的代码的一部分。
$tags = explode(",", $_POST['tag']);
回答by VolkerK
E.g. via array_filter()or by using the PREG_SPLIT_NO_EMPTY option on preg_split()
例如通过array_filter()或使用preg_split()上的 PREG_SPLIT_NO_EMPTY 选项
<?php
// only for testing purposes ...
$_POST['tag'] = ",jay,john,,,bill,glenn,,0,,";
echo "--- version 1: array_filter ----\n";
// note that this also filters "0" out, since (bool)"0" is FALSE in php
// array_filter() called with only one parameter tests each element as a boolean value
// see http://docs.php.net/language.types.type-juggling
$tags = array_filter( explode(",", $_POST['tag']) );
var_dump($tags);
echo "--- version 2: array_filter/strlen ----\n";
// this one keeps the "0" element
// array_filter() calls strlen() for each element of the array and tests the result as a boolean value
$tags = array_filter( explode(",", $_POST['tag']), 'strlen' );
var_dump($tags);
echo "--- version 3: PREG_SPLIT_NO_EMPTY ----\n";
$tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY);
var_dump($tags);
prints
印刷
--- version 1: array_filter ----
array(4) {
[1]=>
string(3) "jay"
[2]=>
string(4) "john"
[5]=>
string(4) "bill"
[6]=>
string(5) "glenn"
}
--- version 2: array_filter/strlen ----
array(5) {
[1]=>
string(3) "jay"
[2]=>
string(4) "john"
[5]=>
string(4) "bill"
[6]=>
string(5) "glenn"
[8]=>
string(1) "0"
}
--- version 3: PREG_SPLIT_NO_EMPTY ----
array(5) {
[0]=>
string(3) "jay"
[1]=>
string(4) "john"
[2]=>
string(4) "bill"
[3]=>
string(5) "glenn"
[4]=>
string(1) "0"
}
回答by Kachi Eze
$tags = array_diff(explode(",", $_POST['tag']),array(""));
回答by Haroldo
//replace multiple commas
$tags = preg_replace('/,+/', ',', $_POST['tag']);
//explode
$tags = explode(',', $tags);
回答by Faisal
Simply try:
只需尝试:
$tags = explode(", ", $_POST['tag']);
Adding space after comma, does the job!
在逗号后添加空格,就可以了!