Strip URL to domain name


/ Published in: PHP
Save to your folder(s)

Alternative to
[http://snipplr.com/view/12616/strip-url-to-its-domain-name/](http://snipplr.com/view/12616/strip-url-to-its-domain-name/, "this snippet"), as it didn't come out clearly in the comments.

Update - Edited based on gdvickery's comment - thanks!

Also added a test case so people can see how it works.


Copy this code and paste it in your HTML
  1. <?
  2.  
  3. $url[0] = " http://www.google.com/test ";
  4. $url[1] = "http://www.google.com/and";
  5. $url[2] = "http://web.google.com/bla";
  6. $url[3] = "http://google.com/go/";
  7. $url[4] = "www.google.com/jeep";
  8. $url[5] = "google.com/bam";
  9. $url[6] = "http://google.com/forget";
  10. $url[7] = "mail.google.com";
  11. $url[8] = "google.co.in";
  12. $url[9] = "http://google.co.uk";
  13. $url[10] = "http://mail.google.co.uk";
  14. $url[11] = "google.co.uk/";
  15. $url[12] = "http://mail.google.co.uk/";
  16.  
  17. foreach ( $url as $u ) {
  18. echo stripit($u)."<br>";
  19. }
  20.  
  21.  
  22. /*** this is the stripit function for you copy/pasters out there ***/
  23. function stripit ( $url ) {
  24. $url = trim($url);
  25. $url = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
  26. $url = preg_replace("/\/.*$/is" , "" ,$url);
  27. return $url;
  28. }
  29. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.