【问题标题】:Using preg_split to split with a delimiter OR every x characters使用 preg_split 用分隔符或每 x 个字符分割
【发布时间】:2010-09-20 17:15:41
【问题描述】:

你好||||人满为患 :) 恐怕我在任何地方都找不到答案,所以这里是:

我的代码:

$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);

我的期望:

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

长话短说,如果看不到分隔符,我会尝试在每次出现 ff# 或每 12 个字符时进行拆分。 也欢迎其他建议,只是认为 preg_split 能够做到这一点;我只是很讨厌正则表达式:(

提前感谢您的宝贵时间!

【问题讨论】:

    标签: php regex preg-split


    【解决方案1】:

    快速、现成的解决方案:

    $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;
    }
    

    我相信有人会想出更优雅的东西。

    【讨论】:

    • NUE 的解决方案看起来更小,但这个看起来也很有效,谢谢 :D
    【解决方案2】:

    不需要正则表达式。试试:

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

    产量:

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

    当我试图提出一个正则表达式解决方案时,我想到了这一点:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2013-05-03
      相关资源
      最近更新 更多