在PHP中分别拆分URL和返回组件

时间:2019-03-26 13:02:08

标签: php

我正在尝试将以下动态网址分为以下几个部分。网址可以是以下格式的任何内容。

输入:

https://www.test.com/directory/subdirectory/index.php?qry=4
or 
https://www.test.com/directory/subdirectory/index.php
or 
https://www.test.com/directory/index.php?qry=4
or 
https://www.test.com/directory/index.php
or 
https://www.test.com/index.php?qry=4
or 
https://www.test.com/index.php
or 
https://www.test.com/

输出:

$http_part = "https";
$root_url = "www.test.com";
$subdirectory = "directory/subdirectory";  // if not available blank should be returned
$pagename = "index.php";   // if no page name is available default index.php
$paramerts = "qry=4"; // if not available blank should be returned

我知道我可以使用url解析,但是在所有情况下都不能。

通过输入url可以返回所有这些输出吗?

1 个答案:

答案 0 :(得分:0)

首先在其上运行类似parse_url的内容,然后可以拆分路径并获取目录:

$url = parse_url('https://www.test.com/directory/subdirectory/index.php?qry=4');
$http_part = $url['scheme'];
$root_url = $url['host'];
$paramerts = $url['path'];

$url_parts = explode('/', $url['path']);

您可以根据需要使用$url_parts$subdirectory处理$pagename,但这应该可以帮助您入门。