【发布时间】:2012-09-03 10:15:50
【问题描述】:
我正在尝试使用 php 将字符串拆分为数组组件,使用 " 或 ' 作为分隔符。我只想按最外面的字符串拆分。以下是四个示例以及每个示例的预期结果:
$pattern = "?????";
$str = "the cat 'sat on' the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the cat
[1] => 'sat on'
[2] => the mat
)*/
$str = "the cat \"sat on\" the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the cat
[1] => "sat on"
[2] => the mat
)*/
$str = "the \"cat 'sat' on\" the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the
[1] => "cat 'sat' on"
[2] => the mat
)*/
$str = "the 'cat \"sat\" on' the mat 'when \"it\" was' seventeen";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the
[1] => 'cat "sat" on'
[2] => the mat
[3] => 'when "it" was'
[4] => seventeen
)*/
如您所见,我只想按最外层的引号分割,我想忽略引号内的任何引号。
我为$pattern 想出的最接近的是
$pattern = "/((?P<quot>['\"])[^(?P=quot)]*?(?P=quot))/";
但显然这是行不通的。
【问题讨论】:
标签: php preg-split