0

我想用逗号有力地分割一个列表。按原样,preg_split正在完成基本目标。用户可以输入项目之间的任意组合,[space(s)],[space(s)]列表将成功拆分。

$items = 'one, two , three  ,four,   five';
$items = preg_split('/(\s*,\s*)+/', $items);

这导致正确['one', 'two', 'three', 'four', 'five']。我想对此进行扩充,以允许通过引号转义分隔符,例如:

$items = 'one, "two , three",four,   five';

期望的结果['one', 'two , three', 'four', 'five']

我相信答案是preg_match_all,但似乎无法将拼图与唯一[space(s)],[space(s)]约束放在一起。

请注意,str_getcsv在这种情况下不起作用,因为间距会使最终的字符串倾斜。

4

1 回答 1

2

您正在解析 CSV 字符串,因此您可以使用:

$result = str_getcsv( $items);

这将导致:

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

然后,您可以使用以下方法删除元素周围的所有空白:

$result = array_map( 'trim', $result);
于 2013-08-29T01:43:43.423 回答