2010-08-09 76 views
19

獲取域我想PHP正則表達式:從URL


我想從一個URLdomain部分得到什麼所以從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中發現了一些相關的問題,但沒有一個是我正在尋找的。

感謝您的幫助!

+0

此代碼將幫助您獲取完整的域名:https://gist.github.com/praisedpk/64bdb80d28144aa78d58469324432277 – 2016-09-18 20:27:25

回答

69

有沒有必要使用這個正則表達式。 PHP有一個內置函數來做到這一點。使用parse_url()

$domain = parse_url($url, PHP_URL_HOST); 
+1

你做了一個魔術師。給出一個很好的解決方案。 – 2013-11-28 14:43:47

+1

它只有包含http(s),不適用於「stackoverflow.com/questions」 – ewwink 2014-01-27 05:20:48

+1

這也會給你子域名。要小心,因爲'parse_url('http://example.com',PHP_URL_HOST)== parse_url('http://www.example.com',PHP_URL_HOST)'將返回false – 2015-05-13 22:30:51

0

這是我的快速和骯髒的解決方案。

http://([^/]+).*

我沒有測試它,但它應該抓住http://和第一個斜槓之間的任何東西。

+1

有關http:// www的域如何? – User 2014-03-28 19:28:15

1

假設http://是前綴。

$tmp = explode("/", $url); 
$domain = $tmp[2]; 
+0

heh,最現成的解決方案:-) – gnud 2010-08-09 18:01:33

0
if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) { 
    $domain = $matches[1]; 
} 
1
$tmp = parse_url($url); 
$url = $tmp['host'] 
1

這就好比regex from theraccoonbear但與HTTPS域的支持。

if (preg_match('/https?:\/\/([^\/]+)\//i', $target_string, $matches)) { 
    $domain = $matches[1]; 
} 
0

最好的方式,我認爲:

preg_match('/(http(|s)):\/\/(.*?)\//si', 'http://www.example.com/page/?bla=123#[email protected]#$%^&*()_+', $output); 
// $output[0] ------------> https://www.example.com/ 
2

我用:

$domain = parse_url('http://' . str_replace(array('https://', 'http://'), '', $url), PHP_URL_HOST); 

因爲parse_url不返回主機密鑰模式時,在$url丟失。