PHP 将URL拆分为协议,站点和资源部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 将URL拆分为协议,站点和资源部分相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Takes an URL and splits it up into it's protocol, site, and resource parts
 * 
 * Returns an associative array of protocol, port, site, and resource parts
 * Note: the URL does not have to have a protocol specified 
 * example:
 * <code>
 *     $url = "http://www.foo.com/blog/search?q=bar";
 *     $url_parts = getUrlParts($url);
 *     // $url_parts will contain the following:
 *     // Array
 *     // (
 *     //     [protocol] => http
 *     //     [port] =>
 *     //     [site] => www.foo.com
 *     //     [resource] => blog/search?q=bar
 *     // )
 *     
 *     $url = "www.foo.com:8080/blog/search?q=bar";
 *     $url_parts = getUrlParts($url);
 *     // $url_parts will contain the following:
 *     // Array
 *     // (
 *     //     [protocol] =>
 *     //     [port] => 8080
 *     //     [site] => www.foo.com
 *     //     [resource] => blog/search?q=bar
 *     // )
 * </code>
 * 
 * @param string	The URL that you want to split up
 * @return associative array 	Array containing the split up parts of the URL
 */
function getUrlParts($url) {
	$result = array();
	
	// Get the protocol, site and resource parts of the URL
	// original url = http://example.com/blog/index?name=foo
	// protocol = http://
	// site = example.com/
	// resource = blog/index?name=foo
	$regex = '#^(.*?//)*([\w\.\d]*)(:(\d+))*(/*)(.*)$#';
	$matches = array();
	preg_match($regex, $url, $matches);
			
	// Assign the matched parts of url to the result array
	$result['protocol'] = $matches[1];
	$result['port'] = $matches[4];
	$result['site'] = $matches[2];
	$result['resource'] = $matches[6];
	
	// clean up the site portion by removing the trailing /
	$result['site'] = preg_replace('#/$#', '', $result['site']);
	
	// clean up the protocol portion by removing the trailing ://
	$result['protocol'] = preg_replace('#://$#', '', $result['protocol']);
	
	return $result;
}
?>

以上是关于PHP 将URL拆分为协议,站点和资源部分的主要内容,如果未能解决你的问题,请参考以下文章

将url拆分为多个部分

url是指啥

PHP 获取站点 URL 协议 - http 与 https

url是啥意思?

PHP PHP将数字拆分为整数和小数部分

php 示例导出脚本,用于将MODX资源转换为CSV条目,以便在另一个站点中导入。