regexp用逗号和空格分隔字符串,但忽略内部引号和括号 [英] regexp split string by commas and spaces, but ignore the inside quotes and parentheses

查看:158
本文介绍了regexp用逗号和空格分隔字符串,但忽略内部引号和括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用逗号和空格分隔字符串,但忽略内部引号,单引号和括号

I need split string by commas and spaces, but ignore the inside quotes, single quotes and parentheses

$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]*[^\w\s]+[\s]*/", $str,0,PREG_SPLIT_NO_EMPTY);

但是这忽略了特殊的字符,并且斯蒂尔将引号内的逗号分开,结果数组为:

but this is ignoring special chars and stil split the commas inside quotes, the resultant array is :


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

ps:这不是csv

ps: this is no csv

非常感谢

推荐答案

这仅适用于非嵌套括号:

This will work only for non-nested parentheses:

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

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

++*+将消耗尽可能多的能量,并且不退回任何东西进行回溯. perlre(1)中描述了这种技术,它是进行这种匹配的最有效方法.

The ++ and *+ will consume as much as they can and give nothing back for backtracking. This technique is described in perlre(1) as the most efficient way to do this kind of matching.

这篇关于regexp用逗号和空格分隔字符串,但忽略内部引号和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆