我想要什么
我想从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 |
+----------------------------------------------+-----------------------+
示例:
stackoverflow
我在{{1}}中找到了一些相关问题,但这些问题都不是我想要的。
感谢您的帮助!
答案 0 :(得分:73)
没有必要为此使用正则表达式。 PHP有一个内置函数来做到这一点。使用parse_url()
:
$domain = parse_url($url, PHP_URL_HOST);
答案 1 :(得分:2)
我用:
$domain = parse_url('http://' . str_replace(array('https://', 'http://'), '', $url), PHP_URL_HOST);
因为parse_url
中缺少架构时$url
未返回主机密钥。
答案 2 :(得分:1)
假设http://
为所有内容添加前缀。
$tmp = explode("/", $url);
$domain = $tmp[2];
答案 3 :(得分:1)
$tmp = parse_url($url);
$url = $tmp['host']
答案 4 :(得分:1)
这与regex from theraccoonbear类似,但支持HTTPS域。
if (preg_match('/https?:\/\/([^\/]+)\//i', $target_string, $matches)) {
$domain = $matches[1];
}
答案 5 :(得分:0)
这是我快速而又肮脏的解决方案。
http://([^/]+).*
我没有测试过它,但它应该在http://
和第一个斜杠之间抓取任何东西。
答案 6 :(得分:0)
if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) {
$domain = $matches[1];
}
答案 7 :(得分:0)
preg_match('/(http(|s)):\/\/(.*?)\//si', 'http://www.example.com/page/?bla=123#!@#$%^&*()_+', $output);
// $output[0] ------------> https://www.example.com/
答案 8 :(得分:0)
我认为以下正则表达式可能会回答您的问题。
This diagram解释了它是如何工作的,或者是为什么它:-)
$regexp = '/.*\/\/([^\/:]+).*/';
// www.stackoverflow.com
echo preg_replace($regexp, '$1', 'http://www.stackoverflow.com/questions/ask');
// google.de
echo preg_replace($regexp, '$1', 'http://google.de/?q=hello');
// it works for the other input tests too ;-)