例如,我想从这个字符串中的元素创建一个数组:

$str = 'red,     green,     blue ,orange';

我知道你可以通过爆炸和循环,并修剪:

$arr = explode(',', $str);
foreach ($arr as $value) {
    $new_arr[] = trim($value);
}

但我觉得有一种方法可以解决这个问题。什么好主意吗?


当前回答

修剪和爆炸

$str = '红色,绿色,蓝色,橙色';

$str = 修剪($str);

$strArray = 爆炸(',',$str);

print_r ($ strArray);

其他回答

使用array_map可以完成以下操作:

$new_arr = array_map('trim', explode(',', $str));
$str = str_replace(" ","", $str);

你也可以用一行正则表达式来实现

preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);

试试这个:

$str = preg_replace("/\s*,\s*/", ",", 'red,     green,     blue ,orange');

这就是如何在一行代码中替换和爆炸

$str = 'red,     green,     blue ,orange';

$new_string = explode(',',preg_replace('/\s+/', '', $str));

将结果输出为

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => orange
)