我正在尝试使用 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))/";
但显然这是行不通的。