PHP正则表达式强大的逗号分割,忽略引用的项目

时间:2013-08-29 01:41:13

标签: php regex

我想用逗号分隔列表。原样,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在这种情况下不起作用,因为间距会使最终字符串偏斜。

1 个答案:

答案 0 :(得分: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);