PHP REGEX:从URL获取域

Ada*_*dam 20 php regex dns url

我想要的是


我希望从获得URL的domain一部分,所以从http://example.com/- >example.com

例子:


+----------------------------------------------+-----------------------+
| 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             |
+----------------------------------------------+-----------------------+
Run Code Online (Sandbox Code Playgroud)

我发现了一些相关的问题,stackoverflow但没有一个是我正在寻找的.

谢谢你的帮助!

cle*_*tus 74

没有必要使用正则表达式.PHP有一个内置函数来做到这一点.用途parse_url():

$domain = parse_url($url, PHP_URL_HOST);
Run Code Online (Sandbox Code Playgroud)

  • 只有包含http(s),而不是"stackoverflow.com/questions"才有用 (2认同)