Alex Rivera | Logout

PHP REGEX: Get domain from URL

Asked 2010-08-09T17:00:23.483
24

What I want


I want to get from a URL the domain part so from http://example.com/ -> example.com

Examples:


+----------------------------------------------+-----------------------+
| input                                        | output                |
+----------------------------------------------+-----------------------+
| http://www.stackoverflow.com/questions/ask   | www.stackoverflow.com |
| http://validator.w3.org/check                | validator.w3.org      |
| http://www.google.com/?q=hello               | www.google.com        |
| http://google.de/?q=hello                    | google.de             |
+----------------------------------------------+-----------------------+

I found some related questions in stackoverflow but none of them was exactly what I was looking for.

Thanks for any help!

Edit
Report

1 Answer

0
if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) {
  $domain = $matches[1];
}
answered 2010-08-09T17:05:13.303

Your Answer