dsfg3241 2013-08-29 01:41
浏览 29
已采纳

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

I would like to robustly split a list by commas. As-is, preg_split is accomplishing the basic goal. The user can enter any combination of [space(s)],[space(s)] between items and the list will split out successfully.

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

This results in ['one', 'two', 'three', 'four', 'five'] correctly. I would like to augment this to allow for escaped delimiters via quotations, e.g.:

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

Desired result of ['one', 'two , three', 'four', 'five']

I believe the answer is in preg_match_all, but can't seem to put the puzzle pieces together with the unique [space(s)],[space(s)] constraint.

Note that str_getcsv doesn't work in this case, as the spacing will skew the final strings.

  • 写回答

1条回答 默认 最新

  • duanlu8613 2013-08-29 01:43
    关注

    You're parsing a CSV string, so you can use:

    $result = str_getcsv( $items);
    

    This will result in:

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

    You can then remove all of the whitespace surrounding the elements with:

    $result = array_map( 'trim', $result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口