Tags
PHP
Asked 8 years ago
30 Sep 2016
Views 2025
kord

kord posted

How to find hostname with regex in php ?

using following code to get hostname from given url

$url="http://hostname.com/contact-us.html";
$url_piece=explode("/",$url);
echo $hostname=$url_piece[2];


Result:

hostname.com


but i dont find it proper , i want to do it betterly with regex so suggest some code with preg_match

Thanks
Yes you are right . its not look good , - jagdish  
Sep 30 '16 07:50
debugger

debugger
answered Nov 30 '-1 00:00

No explode or no regex . i used string functions to get domain from given Url


$url="http://hostname.com/contact-us.html";
echo $domain = strstr(substr(strstr($url, '//'),2),"/",true);// try it on >=php 5.3.0


Result::

hostname.com


Explaination (how above code work)::
strstr give us first occurrence of a string so with "//" it give me "//hostname.com/contact-us.html"" , substr used to get rid of "//" and again used strstr with "/" and used option parameter to "true" to so i get the haystack before the first occurrence and its our hostname .
so code

$url="http://hostname.com/contact-us.html";
strstr()

Result::

//hostname.com/contact-us.html
hostname.com/contact-us.html
hostname.com

thanks its good help . and good explanation , still need regex - kord  
Sep 30 '16 09:04
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

find hostname with regex code


$url="http://hostname.com/contact-us.html"; 
preg_match('@^(?:http://|https://)?([^/]+)@i',$url, $matches);
echo $host = $matches[1];

Result::

hostname.com


Hope it help
thumbs up . its good thanks - kord  
Sep 30 '16 09:07
Post Answer