Skip to content
Advertisement

Php Regex: how to match repeated patterns

given following text

bond0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
eth0: 11329920252 12554462    0    0    0     0          0      3561 13072970332 12899522    0    0    0     0       0          0

I need to capture columns values. I thought something about these lines:

Regex: `(w+):(?:s+(d+))+`
Php: `preg_match_all('/(w+):(?:s+(d+))+/sim', $data, $regs)

But unfortunately it captures only first column.

Array
(
    [0] => Array
        (
            [0] => dummy0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
            [1] => bond0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
            [2] => eth0: 11329920252 12554462    0    0    0     0          0      3561 13072970332 12899522    0    0    0     0       0          0
            [3] => ip6tnl0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
            [4] => lo: 51675995  100695    0    0    0     0          0         0 51675995  100695    0    0    0     0       0          0
            [5] => sit0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
            [6] => tunl0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
        )

    [1] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
        )

)

Any suggestion? Thanks `

====EDIT==== Just to be clear: i know that i could preg_match searching for d+ values or split the whole string in lines and run explode on the each line, but I’m interested in regex solution where I have first column as first member of resulting array(actualy forgot to put capturing braces in the first draft of question), and following columns with data, every line putted in it’s dedicated array…

Advertisement

Answer

Why use preg_match or preg_match_all at all?

$results = array();
foreach (preg_split("/rn|r|n/", $data) as $line)
{
    list($key, $values) = explode(":", $line);
    $results[$key] = preg_split("/s/", trim($values));
}

This should work as long as there is no more than one : on every line. Seems to me like it’s the shortest and fastest way to write this too.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement