PHP,正则表达式和多级破折号,并根据出现的字符串分组 [英] PHP, regex and multi-level dashes and grouping together according to string occurrence

查看:109
本文介绍了PHP,正则表达式和多级破折号,并根据出现的字符串分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的字符串:

I have a string which looks like this:

15-02-01-0000 
15-02-02-0000
15-02-03-0000 
15-02-04-0000 
15-02-05-0000 
15-02-10-0000 
15-02-10-9100 
15-02-10-9101 
15-15-81-0000 
15-15-81-0024

因此,预期输出为: 所有帐户分组均以-"破折号分隔,例如:15-02-01-0000共有3个分组

So the expected output would be: All account grouping separated by "-" dashes for example: 15-02-01-0000 there is 3 grouping

  • 从15开始
  • 从15-02开始
  • 从15-02-01开始

所以预期的输出将是:

首先它将显示

15  --> All account start with "15"
  15-02 --> All account start with "15-02"
    15-02-01 -- All accounts start with "15-02-01"
      15-02-01-0000 
    15-02-02 -- All accounts start with 15-02-02
      15-02-02-0000
    15-02-03 -- onwards like above
      15-02-03-0000 
    15-02-04 
      15-02-04-0000 
    15-02-05 
      15-02-05-0000 
    15-02-10 
      15-02-10-0000 
      15-02-10-9100 
      15-02-10-9101 
  15-15 
    15-15-81 
      15-15-81-0000 
      15-15-81-0024

我尝试使用substr:

$res = substr("15-15-81-0024",3,2);
if ($res == "15") {

} else if ($res < 10 && $res != 00) {

} else {

}

但无法进行分组. 你能建议什么好方法吗?

But not working to put grouping. Could you please suggest any good way?

推荐答案

您可以按-分解每个数据,并根据需要构建数组.请注意,在代码中使用 & 作为对结果数组的引用.

You can break each data by - and build the array in as much as needed. Notice the use of & in the code as using reference to result array.

示例:

$str = "15-02-01-0000,15-02-02-0000,15-02-03-0000,15-02-04-0000,15-02-05-0000,15-02-10-0000,15-02-10-9100,15-02-10-9101,15-15-81-0000,15-15-81-0024";
$arr = explode(",", $str);
$res = [];
foreach($arr as $e) { // for each line in your data
    $a = explode("-", $e); //break to prefix
    $current = &$res; 
    while(count($a) > 1) { // create the array to that specific place if needed
        $key = array_shift($a); // take the first key
        if (!isset($current[$key])) // if the path not exist yet create empty array 
            $current[$key] = array();
        $current = &$current[$key];
    }
    $current[] = $e; // found the right path so add the element
}

完整结果将在$res中.

这篇关于PHP,正则表达式和多级破折号,并根据出现的字符串分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆