解析url的3個php函數
通過url進行傳值,是php中一個傳值的重要手段。所以我們要經常對url裡面所帶的參數進行解析,如果我們知道了url傳遞參數名稱,例如
/index.php?name=tank&sex=1#top
我們就可以通過$_GET['name'],$_GET['sex']來獲得傳的資料。但是如果我們不知道這些變數名又怎麼辦呢?這也是寫這篇博文的目的,因為自己老是忘,所以做個標記,下次就不要到處找了。
我們可以通php的變數來獲得url和要傳的參數字串
$_SERVER["QUERY_STRING"] name=tank&sex=1
$_SERVER["REQUEST_URI"] /index.php?name=tank&sex=1
javascript也可以獲得來源的url,document.referrer;方法有很多
1,利用pathinfo
1.2.$test = pathinfo("http://localhost/index.php");??
3.print_r($test);??
4.?>??
5.結果如下??
6.Array??
7.(??
8.??? [dirname] => http://localhost //url的路徑??
9.??? [basename] => index.php? //完整檔案名稱??
10.??? [extension] => php? //檔案名稱尾碼??
11.??? [filename] => index //檔案名稱??
12.)?
$test = pathinfo("http://localhost/index.php");
print_r($test);
?>
結果如下
Array
(
??? [dirname] => http://localhost //url的路徑
??? [basename] => index.php? //完整檔案名稱
??? [extension] => php? //檔案名稱尾碼
??? [filename] => index //檔案名稱
)2,利用parse_url
1.2.$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");??
3.print_r($test);??
4.?>??
5.結果如下??
6.Array??
7.(??
8.??? [scheme] => http //使用什麼協議??
9.??? [host] => localhost //主機名稱??
10.??? [path] => /index.php //路徑??
11.??? [query] => name=tank&sex=1 // 所傳的參數??
12.??? [fragment] => top //後面根的錨點??
13.)?
$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
print_r($test);
?>
結果如下
Array
(
??? [scheme] => http //使用什麼協議
??? [host] => localhost //主機名稱
??? [path] => /index.php //路徑
??? [query] => name=tank&sex=1 // 所傳的參數
??? [fragment] => top //後面根的錨點
)3,利用basename
1.2.$test = basename("http://localhost/index.php?name=tank&sex=1#top");??
3.echo $test;??
4.?>??
5.結果如下??
6.index.php?name=tank&sex=1#top?
$test = basename("http://localhost/index.php?name=tank&sex=1#top");
echo $test;
?>
結果如下
index.php?name=tank&sex=1#top上面三種方法,我們基本上,就可以得我們所要的東西了。其實還有一種方法就是用正則,也可以很快的得到我們想到的資料。
傳遞的參數方式有很多,但是主要有這二種,一種是,name=tank&sex=1#top;一種是,name=tank&sex=1。
1.2.preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);??
3.print_r($match);?>??
4.結果如下??
5.Array??
6.(??
7.??? [0] => Array??
8.??????? (??
9.??????????? [0] => name=tank??
10.??????????? [1] => sex=1#top??
11.??????? )??
12.??? [1] => Array??
13.??????? (??
14.??????????? [0] => name=tank??
15.??????????? [1] => sex=1??
16.??????? )??
17.??? [2] => Array??
18.??????? (??
19.??????????? [0] =>??
20.??????????? [1] => #top??
21.??????? )??
22.)?
preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
print_r($match);?>
結果如下
Array
(
??? [0] => Array
??????? (
??????????? [0] => name=tank
??????????? [1] => sex=1#top
??????? )
??? [1] => Array
??????? (
??????????? [0] => name=tank
??????????? [1] => sex=1
??????? )
??? [2] => Array
??????? (
??????????? [0] =>
??????????? [1] => #top
??????? )
)要的資料都匹配出來了,好長時間搞正則了,手都有點生了。上面正則中的規則不是死的,規則是根據url來推測的。