加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – regexp用逗号和空格分割字符串,但忽略内部引号和括号

发布时间:2020-12-13 21:35:11 所属栏目:PHP教程 来源:网络整理
导读:我需要用逗号和空格分割字符串,但忽略内部引号,单引号和括号 $str = "Questions,"Quote",'single quote','comma,inside' (inside parentheses) space #specialchar"; 这样得到的数组就会有 [0]Questions[1]Quote[2]single quote[3]comma,inside[4]inside p
我需要用逗号和空格分割字符串,但忽略内部引号,单引号和括号

$str = "Questions,"Quote",'single quote','comma,inside' (inside parentheses) space #specialchar";

这样得到的数组就会有

[0]Questions
[1]Quote
[2]single quote
[3]comma,inside
[4]inside parentheses
[5]space
[6]#specialchar

我的正常表现是

$tags = preg_split("/[,s]*[^ws]+[s]*/",$str,PREG_SPLIT_NO_EMPTY);

但是这忽略了特殊的字符,stil将逗号分隔在引号内,结果数组为:

[0]Questions
[1]Quote
[2]single quote
[3]comma
[4]inside
[5]inside parentheses
[6]space
[7]specialchar

ps:这不是csv

非常感谢

解决方法

这仅适用于非嵌套括号:

$regex = <<<HERE
    /  "  ( (?:[^"\]++|\.)*+ ) "
     | '  ( (?:[^'\]++|\.)*+ ) '
     | ( ( [^)]*                  ) )
     | [s,]+
    /x
    HERE;

    $tags = preg_split($regex,-1,PREG_SPLIT_NO_EMPTY
                       | PREG_SPLIT_DELIM_CAPTURE);

和*会消耗尽可能多的东西,并且不会回溯任何回溯.这种技术在perlre(1)中被描述为进行这种匹配的最有效方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读