PHP四種URL解析處理方式的例子

在已知URL情況下,以下是四種解析URL的處理方式:

第一種、利用$_SERVER內置數組變量

可以用$_SERVER['QUERY_STRING']來獲取URL的參數,返回類似:name=tank&sex=1

如果需要包含文件名的話可以使用$_SERVER["REQUEST_URI"],返回類似:/index.php?name=tank&sex=1


第二種、利用pathinfo內置函數
01 <?php
02 $test = pathinfo("http://localhost/index.php");
03 print_r($test);

04 /*
05 結果如下
06 Array
07 (
08     [dirname] => http://www.zhuoma.com/index.php     //url的路徑
09     [basename] => index.php                                         //完整文件名
10     [extension] => php                                                  //文件名後綴
11     [filename] => index                                               //文件名
12 )
13 */
14 ?>


第三種、利用parse_url內置函數
01 <?php
02 $test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
03 print_r($test);
04 /*
05 結果如下
06 Array
07 (
08     [scheme] => http //使用什麼協議
09     [host] => localhost //主機名
10     [path] => /index.php //路徑
11     [query] => name=tank&sex=1 // 所傳的參數
12     [fragment] => top //後面根的錨點
13 )
14 */

15 ?>


第四種、利用basename內置函數
1 <?php
2 $test = basename("http://www.zhuoma.com/index.php?name=tank&sex=1#top");
3 echo $test;
4 /*
5 結果如下
6 index.php?name=tank&sex=1#top
7 */
8 ?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章