Search code examples
phpregexpreg-split

Using preg_split to split with a delimiter OR every x characters


Hello ||||overflow crowd :) I'm afraid I couldn't find an answer anywhere, so here goes:

My code:

$stuff = '00#00#e0#12#ff#a3#00#01#b0#23#91#00#00#e4#11#ff#a2#'; //not exact, just a random example
$output = preg_split('/(?:[a-f0-9#]{12}| ff# )/', $stuff);

My expectations:

Array
(
    [0] => 00#00#e0#12#
    [1] => a3#00#01#b0#
    [2] => 23#91#00#00#
    [3] => e4#11##
    [4] => a2#
)

Long story short, I'm trying to split on every occurance of ff# or every 12 characters if there's no delimiter in sight. Alternative suggestions are welcome as well, just thought preg_split would be able to do that; I just suck at regex :(

Thanks in advance for your time!


Solution

  • No regex needed. Try:

    $result = array();
    foreach (explode('ff#', $stuff) as $piece) {
        $result = array_merge($result, str_split($piece, 12));
    }
    
    print_r($result);
    

    Yields:

    Array
    (
        [0] => 00#00#e0#12#
        [1] => a3#00#01#b0#
        [2] => 23#91#00#00#
        [3] => e4#11#
        [4] => a2#
    )
    

    This came to mind when I tried to come up with a regex solution:

    square peg