首页 > 解决方案 > 用逗号分解字符串,再用空格分解

问题描述

我有一串数字,如下所示:

$numbers = "one, two, three four, five";

我首先用逗号将其分解:

$numbers_array = explode(",", $numbers);

我的结果是:

array(4) {
  [0] => string(3)  "one"
  [1] => string(4)  " two"
  [2] => string(11) " three four"
  [3] => string(5)  " five"
}

我的问题是,我怎样才能做到这一点?

array(5) { 
  [0] => string(3) "one" 
  [1] => string(4) "two" 
  [2] => string(6) "three" 
  [3] => string(5) "four" 
  [4] => string(5) "five"
}

标签: phparraystrimexplode

解决方案


这应该将您的代码拆分为空格和逗号:

$numbers = "one, two, three four, five";

$numbers_array = preg_split("/[\s,]+/", $numbers);

然后,您可以通过执行以下操作删除空项目:

$filtered_numbers_array = array_filter($numbers_array);

推荐阅读