Please tell me any function or reg exp to get the subdomain name from full url. Say url is: http://subdomain.mydomain.com http://www.subdomain.mydomain.com subdomain.mydomain.com in all above URL cases i should echo subdomain
Say url is: http://subdomain.mydomain.com http://www.subdomain.mydomain.com subdomain.mydomain.com www is a subdomain subdomain.mydomain and www.subdomain.mydomain are two different subdomains.
Throw this into a test.php file, I think this is what you want ? <?php $domain = "http://www.this-subdomain.mydomain.com"; $regex = "#^([a-z0-9][a-z0-9\-]{1,63})\.[a-z\.]{2,63}$#i"; $domain = str_replace('http://', '', $domain); $domain = str_replace('www.', '', $domain); preg_match($regex, $domain, $matches); echo "If it exist remove the http:// & www. to make the domain : ", $matches[0]," <br />"; echo "We then searched for the subDomain, and found : ", $matches[1]," <br />"; ?> PHP: Out-Put: If it exist remove the http:// & www. to make the domain : this-subdomain.mydomain.com We then searched for the subDomain, and found : this-subdomain Code (markup): So you echo $matches[1] for subDomain
<?php $url = 'http://subdomain.mydomain.com'; $pattern = '(?:http://)?'; //protocol (optional) $pattern .= '(?:www\.)?'; //www. (optional) $pattern .= '([^\.]+)'; //subdomain $pattern .= '\.[^\.]+\.'; //domain $pattern .= '[^ ]+'; //tld preg_match("~{$pattern}~i", $url, $a); echo htmlspecialchars($a[1]); ?> PHP: or simplified: <?php $url = 'http://subdomain.mydomain.com'; $pattern = '(?:http://)?'; //protocol (optional) $pattern .= '(?:www\.)?'; //www. (optional) $pattern .= '([^\.]+)'; //subdomain $pattern .= '[^ ]+'; //the rest... preg_match("~{$pattern}~i", $url, $a); echo htmlspecialchars($a[1]); ?> PHP: