i'm trying to use php to split a string into array components using either "
or '
as the delimiter. i just want to split by the outermost string. here are four examples and the desired result for each:
$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
)*/
as you can see i only want to split by the outermost quotation, and i want to ignore any quotations within quotations.
the closest i have come up with for $pattern
is
$pattern = "/((?P<quot>['\"])[^(?P=quot)]*?(?P=quot))/";
but obviously this is not working.
You can use just
preg_match
for this:This prints:
Here is an explanation of the regex:
/^([^\'"]*)
=> put the initial bit until the first quote (either single or double) in the first captured group(([\'"]).*\3)
=> capture in \2 the text corresponding from the initial quote (either single or double) (that is captured in \3) until the closing quote (that must be the same type as the opening quote, hence the \3). The fact that the regexp is greedy by nature helps to get from the first quote to the last one, regardless of how many quotes are inside.(.*)$/
=> Capture until the end in \4You can use back references and ungreedy modifier in
preg_match_all
Now you have your outermost quotation parts
And you can find the rest of the string with
substr
andstrpos
(kind of blackbox solution)Here is the result
Just strip eventual empty heading/trailing element if the quotation is at the very beginning/end of the string.
You can use
preg_split
with thePREG_SPLIT_DELIM_CAPTURE
option. The regular expressions is not quite as elegant as @Jan Turoň's back reference approach because the required capture group messes up the results.Yet another solution using preg_replace_callback
Now you can zip those arrays using
array_map
And the result is
Note: I'd would be probably better to create a class doing this feat, so the global variables can be avoided.