I've searched for hours, and I can't seem to find a way to do this. I want to parse an input string (google.com), set a PHP variable corresponding to the TLD in the string, and remove the TLD from the string. ie: input 1 = google.com input 2 = google.net Lets say I'm inputting input 1 first, and input 2 next. I want this script to set a variable (.com = $com, .net = $net) to the TLD in the string, and remove the TLD from the string, setting the string to a new variable ($parseddomain). This would leave me with a string of google and a $com or $net variable. How can I do this? Sorry if this is confusing, I'm a PHP noob
Heres a function I took from a project I did over a year ago: function get_tld($url) { $url = trim($url); if (!preg_match('~^http://~i', $url)) $url = "http://{$url}"; $domain = parse_url($url, PHP_URL_HOST); $domain = preg_replace('~^www\.~', NULL, strtolower($domain)); $parts = explode('.', $domain); return (count($parts) > 2) ? ".{$parts[1]}.{$parts[2]}" : '.' . end($parts); } PHP: Integrate it in your scenario... <?php function get_tld($url) { $url = trim($url); if (!preg_match('~^http://~i', $url)) $url = "http://{$url}"; $domain = parse_url($url, PHP_URL_HOST); $domain = preg_replace('~^www\.~', NULL, strtolower($domain)); $parts = explode('.', $domain); return (count($parts) > 2) ? ".{$parts[1]}.{$parts[2]}" : '.' . end($parts); } $domain = 'google.com'; //.com $tld = get_tld($domain); //google $new_domain = str_replace($tld, NULL, $domain); ?> PHP:
For some reason I keep getting this error: Warning: parse_url(http://) [function.parse-url]: Unable to parse URL in /home2/account/public_html/ams/scriptname.php on line 27... Any suggestions? I modified the code to this: function parse_tld($url) { $url = trim($url); if (!preg_match('~^http://~i', $url)) $url = "http://{$url}"; $inputdomain = parse_url($url, PHP_URL_HOST); $inputdomain = preg_replace('~^www\.~', NULL, strtolower($inputdomain)); $parts = explode('.', $inputdomain); return (count($parts) > 2) ? ".{$parts[1]}.{$parts[2]}" : '.' . end($parts); } $tld = parse_tld($inputdomain); $parseddomain = str_replace($tld, NULL, $inputdomain); PHP: The $inputdomain was defined in the script, its just not shown here.
I am pretty sure it would only throw that error if $inputdomain is null or defined as 'http://' because there is nothing to parse.