string para array, dividido por aspas simples e duplas
Eu estou tentando usar o PHP para dividir uma string em componentes de matriz usando"
ou'
como o delimitador. Eu só quero dividir pela cadeia mais externa. Aqui estão quatro exemplos e o resultado desejado para cada um:
$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
)*/
como você pode ver, eu só quero dividir pela cotação mais externa, e eu quero ignorar quaisquer citações dentro de citações.
o mais próximo que eu tenho para$pattern
é
$pattern = "/((?P<quot>['\"])[^(?P=quot)]*?(?P=quot))/";
mas obviamente isso não está funcionando.