2010-09-20 61 views
1

你好||||溢出人群:) 我怕我找不到任何地方的答案,所以这里有云:使用使preg_split用分隔符或每x个字拆分

我的代码:

$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将能够做到这一点;我只是吮吸正则表达式:(

预先感谢您的时间

回答

1

没有正则表达式需要尝试:

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

这次来到介意当我试图想出一个正则表达式的解决方案:

square peg

+0

这太好了!谢谢! – Herc 2010-09-22 13:27:15

2

快速,现成的,袖口的解决方案:

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

我敢肯定有人会拿出一些更。优雅

+0

NUE的解决方案看起来小,但这个工程太,因为它似乎,感谢的是:d – Herc 2010-09-22 13:26:17

相关问题