星期二, 6月 12, 2012

將url字串的參數轉為array

  1. 取出query部份
    $url = 'http://username:password@hostname/path?arg=value#anchor';
    $urlinfo = parse_url($url);
    ------------------------
    Array
    (
        [scheme] => http
        [host] => hostname
        [user] => username
        [pass] => password
        [path] => /path
        [query] => arg=value
        [fragment] => anchor
    )
  2. 轉成array
    $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

References

沒有留言: