How to parse url using php
How to parse url using php
In certain cases, even in my recent made cpanel plugin, I had to parse the url for me to clear their resource cache. The use cases for this are a lot, there are a lot of manipulation reasons for this as well as solutions.
Scenario
I’ll take the same url from one of our pages:
1 |
$url = "http://www.yourhowto.net/how-to-strip-spaces-out-of-a-string-in-perl/"; |
Solution
I used for this the parse_url function from php, it will give us an array of all the parts from our url:
1 2 |
$url_array = parse_url($url); var_dump($url_array); |
Output result
1 2 3 4 5 6 7 8 |
array(3) { ["scheme"]=> string(4) "http" ["host"]=> string(17) "www.yourhowto.net" ["path"]=> string(45) "/how-to-strip-spaces-out-of-a-string-in-perl/" } |
Using the array result
From there, you can use the array elements exactly as you wanted / needed. For instance, if you just need the full url, you can use:
1 2 |
$url_purge = "http://" . $url_array['host'].$url_array['path']; print($url_purge); // Output will be: http://www.yourhowto.net/how-to-strip-spaces-out-of-a-string-in-perl/ |
That’s it for this, quick, easy and simple!