Posted By

xtheonex on 02/26/09


Tagged


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

umang_nine
vali29
BrianCoyDesign
wirenaught


Strip URL to its domain name...


 / Published in: PHP
 

This is a function i created to basically stip a url down to its domain name and nothing else. For eg. If you passed it any of the following urls it would return the same value. http://www.google.com/ www.google.com http://www.google.com/search?hl=en&q=jadeyo&btnG=Google+Search&meta= All of the above urls would return the same varibale of 'google.com'

  1. function striptodomain($url) {
  2. if ((substr_count($url, 'http://www.')) > 0) {
  3. $url = str_replace('http://www.', '', $url);
  4. } elseif ((substr_count($url, 'http://')) > 0) {
  5. $url = str_replace('http://', '', $url);
  6. } elseif ((substr_count($url, 'www.')) > 0) {
  7. $url = str_replace('www.', '', $url);
  8. }
  9. if ((substr_count($url, '/')) > 0) {
  10. $url = substr($url, 0, strrpos($url, '/'));
  11. }
  12. return $url;
  13. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: dsntos on February 26, 2009

Or you can use this:

$url= $SERVER['HTTPHOST'];

Posted By: xtheonex on February 27, 2009

Omg. How much of a retard do i feel now?! :P I Googled for an easy way of doing this and nothing came up so i created my own function, lol.

Posted By: xtheonex on February 27, 2009

Actually. No. That will only get the domain name of the host. My function, stips down any url passed to it. For eg. i used my function to standardize any urls submitted by users.

Posted By: duniyadnd on February 27, 2009

Did you just want to contain the domain's information without the subdomain www? Some site's use www. as a subdomain so you may want to include that. It's a good script, and pretty speedy, here's an alternative if you would prefer:

function stripit ( $url ) { $url = trim($url); $url = pregreplace("/^(http:\/\/)(www.)/is", "", $url); $url = pregreplace("/\/.*$/is" , "" ,$url); return $url; }

Created a test for this and yours as well - btw, I just noticed that you have a problem for $url[3]. Don't know if you wanted to keep the sub-directory or not.

$url[0] = " http://www.google.com/test "; $url[1] = "http://www.google.com/and"; $url[2] = "http://web.google.com/bla"; $url[3] = "http://google.com/go/"; $url[4] = "www.google.com/jeep"; $url[5] = "google.com/bam"; $url[6] = "http://google.com/forget"; $url[7] = "mail.google.com"; $url[8] = "google.co.in"; $url[9] = "http://google.co.uk"; $url[10] = "http://mail.google.co.uk"; $url[11] = "google.co.uk/"; $url[12] = "http://mail.google.co.uk/";

foreach ( $url as $u ) { echo $u.""; echo striptodomain($u).""; echo stripit($u).""; }

You need to login to post a comment.