duanque2413
2012-06-16 09:22
浏览 48
已采纳

在PHP中用逗号分解复杂的字符串

I need to split a string that contains commas. I already found something for strings like (str_getcsv):

'A', 'B with a comma, eh', 'C'

But my string is like this, e.g. with no enclosing characters for the values:

A, B (one, two), C

I need to explode this and obtain:

array(3) {
  [0]=>
  string(1) "A"
  [1]=>
  string(12) "B (one, two)"
  [2]=>
  string(1) "C"
}

I want to split the string using the commas that are not inside parentheses, because that is the only one case in my situation when explode fails.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • douhan8581 2012-06-16 09:40
    最佳回答

    But there is a solution for your crazy wish ;)

    $a = "(Z) X, (Y, W) A, B (one, two), C, D (E,F,G) H, I J";
    $reg = '/[^(,]*(?:\([^)]+\))?[^),]*/';
    preg_match_all($reg, $a, $matches);
    $result = array_filter($matches[0]);
    var_dump($result);
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题