PHP正则表达式和URL解析

时间:2012-12-18 23:44:28

标签: php parsing

如何利用PHP中的preg_replace来解析网址。

说我有网址

http://google.com?id=123

我希望访问网址的每个部分,以便

echo $protocol;

会打印

http

echo $domain;

会打印

google

echo $upperDomain;

打印

com

最后,

echo $rest;

会打印

?id=123

2 个答案:

答案 0 :(得分:4)

有一个功能:parse_url()

$url = 'http://google.com?id=123';    
print_r(parse_url($url));

打印:

Array
(
    [scheme] => http
    [host] => google.com
    [query] => id=123
)

答案 1 :(得分:0)

parse_url() 来自文档...

 mixed parse_url ( string $url [, int $component = -1 ] )

This function parses a URL and returns an associative array containing any of the   
various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the 
above listed parts. Partial URLs are also accepted, parse_url() tries its best to   
parse them correctly. 
相关问题