0

I am trying to split the following dynamic url into several components like below. Url can be anything in the below format.

input:

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/

output:

$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

I know i can use url parsing, but it doesnt in all the situation.

Any function is available by inputting the url which will return all these outputs ?

Durgaprasad
  • 323
  • 2
  • 14
  • PHP has a function for URI parsing (https://www.php.net/manual/en/function.parse-url.php) – Youmy001 Mar 26 '19 at 13:05
  • Yes, I was using php parse url functionality. But it doesnt work in all the type of urls. It doesnt return reliable results – Durgaprasad Mar 26 '19 at 13:07
  • Then make your question about *that* instead of making us assume you simply didn't read the manual and hadn't found this function. `parse_url` works just fine with all the URLs you list: https://3v4l.org/3YBiY – deceze Mar 26 '19 at 13:13

1 Answers1

0

First run something like parse_url on it, then you can split the path up and get the directories:

$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']);

You can handle $url_parts however you like with $subdirectory and $pagename, but this should get you started.

Daniel G
  • 539
  • 4
  • 10