This is just that easy to do as picking up a dollar on the ground.
You can, of course write your own function to parse a string that looks like a URL and return various parts such as the domain, directory, requested file and possible data fields. However, PHP has come with exactly the function you need so you really don’t have to reinvent the wheel.
That is parse_url().
$url_parts = parse_url('https://www.google.com/search?q=obama');
The output looks like:
[scheme] => http
[host] => www.google.com
[path] => /search
[query] => q=obama
The returned is an array containing a breakdown of the given URL. This way not only do you have the host name (www.google.com) but also protocol scheme (http), server path (/search) and query string (q=obama).
Easy enough, huh?
2 thoughts on “How to parse a URL in PHP to get the domain / host name”
Is there a way i can get the localhost of a website using php? please reply
I am one of these “code challenged folks” so even though it seems I found a nice clean piece of php code to use for the purpose of parsing domains, which being and owner of domains it seems like I need to do this regularly;
I was wondering how do use this info:
$nowww = ereg_replace(‘www\.’,”,$url);
$domain = parse_url($nowww);
To parse domains:
Do I need to build some little app that works in a browser or on my desktop? When money got tight I stopped my subscription to estibot and now I guess I really need to “appraise domains” the old fashioned and time consuming way, and then find a nice and easy way to parse my domains out of the “mixed” junk I sometime cut and paste.
Actually come to think of it seems the easiest way to parse the domains out of a “domain list” such as I get at my registrar is just to copy the whole thing and then paste the results into a spreadsheet such as Excel. Then all I need to do is to do a second cut and paste this time scrolling up the column that the domains lined up into.
Comments are closed.