Home > database >  How to parse string in PHP?
How to parse string in PHP?

Time:05-23

I get string from server:

auto  status
        simple.cars  OK
        simple.moto  OK
        authorize.cars  OK
        authorize.moto  OK

I want to parse this by tabulation and get an array key (simple.cars) - value OK.

$math = preg_match_all("/^(.*)[\t\s] (OK|FAIL)$/im", $result, $out);
        var_dump($out);

But it returns me empty array.

CodePudding user response:

Here is one way to build a map containing keys and their OK/FAIL values:

$input = "auto  status\n         simple.cars  OK\n         simple.moto  OK\n         authorize.cars  OK\n 
    authorize.moto  OK";
preg_match_all("/(\S )\s (OK|FAIL)/", $input, $matches);
$map = array();
for ($i=0; $i < sizeof($matches[1]);   $i) {
    $map[$matches[1][$i]] = $matches[2][$i];
}
print_r($map);

This prints:

Array
(
    [simple.cars] => OK
    [simple.moto] => OK
    [authorize.cars] => OK
    [authorize.moto] => OK
)
  •  Tags:  
  • php
  • Related