Regex repeated capturing group in PHP

后端 未结 2 1790
陌清茗
陌清茗 2021-01-26 09:23

i\'m trying to get information from one file with routes, so for this work i chose regex, but i have the problem with the repeted information, for do a better question i will pu

2条回答
  •  醉酒成梦
    2021-01-26 10:12

    I'm afraid you'll need to use another regular expression to get the repeated subpattern matches. So, you could do something like this:

    preg_match_all("/(?:S|R|B|O|A|K|H|P|U|i) +(?:IA|E|N|) +[0-9.]+\/[0-9]+ +via +([0-9.]+), +([a-zA-Z0-9.]+|), +cost +(?:[0-9]+:|)[0-9]+, +age +[0-9]+ +\n((?: +via +[0-9.]+, +(?:[a-zA-Z0-9.]+|) +\n)*)/",$s,$matches,PREG_SET_ORDER);
    foreach($matches as $id=>$match)
    {
        unset($matches[$id][0]);
        if(isset($match[3])) {
            preg_match_all("/ +via +([0-9.]+), +([a-zA-Z0-9.]+|) +\n/",$match[3],$subpatternMatches,PREG_SET_ORDER);
            unset($matches[$id][3]);
            foreach($subpatternMatches as $spmid=>$spm) {
                    unset($subpatternMatches[$spmid][0]);
                    $matches[$id] = array_merge($matches[$id],$subpatternMatches[$spmid]);
            }
        }
    }
    

    Which gets the following data for your example file:

    array(4) {
      [0]=>
      array(6) {
        [0]=>
        string(6) "10.140"
        [1]=>
        string(8) "bond1.30"
        [2]=>
        string(6) "10.141"
        [3]=>
        string(8) "bond1.31"
        [4]=>
        string(6) "10.142"
        [5]=>
        string(8) "bond1.32"
      }
      [1]=>
      array(2) {
        [1]=>
        string(6) "10.140"
        [2]=>
        string(8) "bond1.30"
      }
      [2]=>
      array(2) {
        [1]=>
        string(6) "10.140"
        [2]=>
        string(8) "bond1.30"
      }
      [3]=>
      array(2) {
        [1]=>
        string(6) "10.140"
        [2]=>
        string(8) "bond1.30"
      }
    }
    

提交回复
热议问题