开发者

Using preg_split to split with a delimiter OR every x characters

开发者 https://www.devze.com 2023-01-17 01:44 出处:网络
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 examp

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_sp开发者_C百科lit would be able to do that; I just suck at regex :(

Thanks in advance for your time!


Quick, off-the-cuff solution:

$regex_output = preg_split('/ff#/', $stuff);
$output = Array();
foreach ($regex_output as $string)
{
    while (strlen($string) > 12)
    {
        $output[] = substr($string, 0, 12);
        $string = substr($string, 12);
    }

    $output[] = $string;
}

I'm sure someone will come up with something much more elegant.


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:

Using preg_split to split with a delimiter OR every x characters

0

精彩评论

暂无评论...
验证码 换一张
取 消