我試圖使用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))/";
,但顯然這是行不通的。
我相信你的解決方案更加優雅。 +1 –
那就是我以前的樣子。它的驚人之處在於它不需要反向引用,但非常棒! – mulllhausen
如果我想擴展正則表達式來忽略轉義引號會很容易嗎? 「在上的 '中Cat S \' 例如'$ STR =」在墊子」'應該給'[0] =>的,[1] => '中Cat S \' 在上「,[2] =>此mat'。如果沒有,那麼我會爲此添加一個新的新問題。乾杯! – mulllhausen