Reputation: 35337
Update: first question resolved, was an issue with HTML/browser.
Second question: Is there a way to output the delimiters into a separate array? If I use PREG_SPLIT_DELIM_CAPTURE, it mixes the delimiters into the same array and makes it confusing as opposed to PREG_SPLIT_OFFSET_CAPTURE which designates its own key for the offset.
Code:
$str = 'world=earth;world!=mars;world>venus';
$arr = preg_split('/([;|])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
echo "<pre>";
print_r($arr);
echo "</pre>";
DELIM CAPTURE example:
Array
(
[0] => world=earth
[1] => ;
[2] => world!=mars
[3] => ;
[4] => world>venus
)
OFFSET CAPTURE example:
Array
(
[0] => Array
(
[0] => world=earth
[1] => 0
)
[1] => Array
(
[0] => world!=mars
[1] => 12
)
[2] => Array
(
[0] => world>venus
[1] => 34
)
)
Upvotes: 2
Views: 394
Reputation: 173572
Technically you can't do this, but in this particular case you can do it quite easily after the fact:
print_r(array_chunk($arr, 2));
Output:
Array
(
[0] => Array
(
[0] => world=earth
[1] => ;
)
[1] => Array
(
[0] => world!=mars
[1] => ;
)
[2] => Array
(
[0] => world>venus
)
)
See also: array_chunk()
Upvotes: 2
Reputation: 89557
You can't!
A way is to use preg_match_all
instead of preg_split
to obtain what you want:
$pattern = '~[^;|]+(?=([;|])?)~';
preg_match_all($pattern, $str, $arr, PREG_SET_ORDER);
The idea is to put an optional capturing group in a lookahead that captures the delimiter.
If you want to ensure that the different results are contiguous, you must add this check to the pattern:
$pattern = '~\G[;|]?\K[^;|]+(?=([;|])?)~';
pattern details:
\G # the end of the last match position ( \A at the begining )
[;|]? # optional delimiter (the first item doesn't have a delimiter)
\K # reset all that has been matched before from match result
[^;|]+ # all that is not the delimiter
(?= # lookead: means "followed by"
([;|])? # capturing group 1 (optional): to capture the delimiter
) # close the lookahead
Upvotes: 2
Reputation: 43033
This is what I get from my Chrome browser when I run the PHP code:
<pre>Array
(
[0] => world=earth
[1] => world!=mars
[2] => world<sun [3]=""> world>venus
)
</sun></pre>
So preg_split
function runs fine. It's just a problem in the array dump in HTML.
Upvotes: 1