PHP: Fastest method to parse url params into varia

2019-04-29 10:29发布

问题:

Possible Duplicate:
Parse query string into an array

What's the fastest method, to parse a string of url parameters into a array of accessible variables?

$current_param = 'name=Peter&car=Volvo&pizza=Diavola&....';

//results in a nice array that I can pass:

$result = array ( 
'name'  => 'Peter',
'car'   => 'Volvo',
'pizza' => 'Diavola'
)

I've tested a REGEXP, but this takes way too long. My script needs to parse about 10000+ url's at once sometimes :-(

KISS - keep it simple, stupid

回答1:

Use parse_str().

$current_param = "name=Peter&car=Volvo&pizza=Diavola";
parse_str($current_param, $result);
print_r($result);

The above will output

Array
(
    [name] => Peter
    [car] => Volvo
    [pizza] => Diavola
)


回答2:

the parse_str() can do the trick as you expect

<?php
    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    parse_str($str);
    echo $first;  // value
    echo $arr[0]; // foo bar
    echo $arr[1]; // baz

    parse_str($str, $output);
    echo $output['first'];  // value
    echo $output['arr'][0]; // foo bar
    echo $output['arr'][1]; // baz

    ?>