我需要用逗号和空格分割字符串,但忽略内部引号,单引号和括号
$str = "Questions, \"Quote\",'single quote','comma,inside' (inside parentheses) space #specialchar";
Run Code Online (Sandbox Code Playgroud)
这样得到的数组就会有
[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);
Run Code Online (Sandbox Code Playgroud)
但是这忽略了特殊的字符,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, $str, -1,
PREG_SPLIT_NO_EMPTY
| PREG_SPLIT_DELIM_CAPTURE);
Run Code Online (Sandbox Code Playgroud)
在++和*+会消耗多,因为他们可以和给任何回报的回溯.这种技术在perlre(1)中被描述为进行这种匹配的最有效方式.