Home >Backend Development >PHP Tutorial >PHP parses the URL and gets the parameters in the URL_PHP tutorial

PHP parses the URL and gets the parameters in the URL_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:32:29904browse

<?php

//例举一个URL格式的字符串:
$str = 'http://test.com/testdir/index.php?param1=10&param2=20&param3=30&param4=40&param5=50&param6=60';

//1 用parse_url解析URL,此处是$str
$arr = parse_url($str);
var_dump($arr);

//2 将URL中的参数取出来放到数组里
$arr_query = convertUrlQuery($arr['query']);
var_dump($arr_query);

//3 将 参数数组 再变回 字符串形式的参数格式
var_dump(getUrlQuery($arr_query));


/**  
  * Returns the url query as associative array  
  * @param     string     query  
  * @return     array     params  
  */  
function convertUrlQuery($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param)
    {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;
}

function getUrlQuery($array_query)
{
    $tmp = array();
    foreach($array_query as $k=>$param)
    {
        $tmp[] = $k.'='.$param;
    }
    $params = implode('&',$tmp);
    return $params;
}
?>

Output result:

array (size=4)
  'scheme' => string 'http' (length=4)
  'host' => string 'test.com' (length=8)
  'path' => string '/testdir/index.php' (length=18)
  'query' => string 'param1=10&param2=20&param3=30&param4=40&param5=50&param6=60' (length=59)


array (size=6)
  'param1' => string '10' (length=2)
  'param2' => string '20' (length=2)
  'param3' => string '30' (length=2)
  'param4' => string '40' (length=2)
  'param5' => string '50' (length=2)
  'param6' => string '60' (length=2)


string 'param1=10&param2=20&param3=30&param4=40&param5=50&param6=60' (length=59)


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/755760.htmlTechArticle$param) { $tmp[] = $k.'='.$param; } $params = implode ('',$tmp); return $params;}?> Output result: array (size=4) 'scheme' => string 'http' (length=4) 'host' => string 'test.com' ( ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn