我正在尝试使用 php 将字符串拆分为数组组件,使用以下任一方法"
or '
作为分隔符。我只想按最外面的字符串分割。以下是四个示例以及每个示例所需的结果:
$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
is
$pattern = "/((?P<quot>['\"])[^(?P=quot)]*?(?P=quot))/";
但显然这是行不通的。
您可以使用preg_split
与PREG_SPLIT_DELIM_CAPTURE
选项。正则表达式并不像 @Jan Turoň 的反向引用方法那么优雅,因为所需的捕获组会弄乱结果。
$str = "the 'cat \"sat\" on' the mat the \"cat 'sat' on\" the mat";
$match = preg_split("/('[^']*'|\"[^\"]*\")/U", $str, null, PREG_SPLIT_DELIM_CAPTURE);
print_r($match);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)