PHP解析URL并得到URL中的参数
01 | <?php |
02 | //例举一个URL格式的字符串: |
03 | $str = 'http://test.com/testdir/index.php?param1=10¶m2=20¶m3=30¶m4=40¶m5=50¶m6=60' ; |
04 |
05 | //1.0 用parse_url解析URL,此处是$str |
06 | $arr = parse_url ( $str ); |
07 | var_dump( $arr ); |
08 |
09 |
10 | //2.0 将URL中的参数取出来放到数组里 |
11 | $arr_query = convertUrlQuery( $arr [ 'query' ]); |
12 | var_dump( $arr_query ); |
13 |
14 |
15 | //3.0 将 参数数组 再变回 字符串形式的参数格式 |
16 | var_dump(getUrlQuery( $arr_query )); |
17 |
18 |
19 | /** |
20 | * Returns the url query as associative array |
21 | * |
22 | * @param string query |
23 | * @return array params |
24 | */ |
25 | function convertUrlQuery( $query ) |
26 | { |
27 | $queryParts = explode ( '&' , $query ); |
28 | |
29 | $params = array (); |
30 | foreach ( $queryParts as $param ) |
31 | { |
32 | $item = explode ( '=' , $param ); |
33 | $params [ $item [0]] = $item [1]; |
34 | } |
35 | |
36 | return $params ; |
37 | } |
38 |
39 | function getUrlQuery( $array_query ) |
40 | { |
41 | $tmp = array (); |
42 | foreach ( $array_query as $k => $param ) |
43 | { |
44 | $tmp [] = $k . '=' . $param ; |
45 | } |
46 | $params = implode( '&' , $tmp ); |
47 | return $params ; |
48 | } |
Result: