Question

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
        )

)
Was it helpful?

Solution

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()

OTHER TIPS

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

This is what I get from my Chrome browser when I run the PHP code:

<pre>Array
(
    [0] =&gt; world=earth
    [1] =&gt; world!=mars
    [2] =&gt; world<sun [3]=""> world&gt;venus
)
</sun></pre>

So preg_split function runs fine. It's just a problem in the array dump in HTML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top