2012-03-03 215 views
37

我有完整的URL作爲字符串,但我想刪除在字符串開頭的http://以很好地顯示URL(例如:www.google.com,而不是http://www.google.comPHP的正則表達式來刪除http://字符串

有人可以幫忙嗎?

+3

爲什麼你需要一個正則表達式?爲什麼不只是刪除前7個字符? – 2012-03-03 21:08:01

+0

檢查這一個:http://stackoverflow.com/questions/4875085/php-remove-http-from-link-title – stefandoorn 2012-03-03 21:09:28

+0

@OliCharlesworth:它可以是8個字符以及'https://' – Sarfraz 2012-03-03 21:11:20

回答

111
$str = 'http://www.google.com'; 
$str = preg_replace('#^https?://#', '', $str); 
echo $str; // www.google.com 

這將兩個http://https://

+0

這個伎倆!謝謝! – Casey 2012-03-03 21:12:26

+0

@Casey:不客氣 – Sarfraz 2012-03-03 21:13:00

+0

來自不太瞭解正則表達式的人,這是一個最容易理解和實現解決這個問題的方法之一,謝謝大家。 – 2013-05-08 00:44:36

1

如果你堅持使用正則表達式上:

preg_match("/^(https?:\/\/)?(.+)$/", $input, $matches); 
$url = $matches[0][2]; 
+2

爲了完整起見,我會在http後添加's?'。是的,我知道這不是他的問題。 。 。 :)) – 2012-03-03 21:10:45

+0

好主意,更新。 – Overv 2012-03-03 21:12:20

20

根本不需要正則表達式。改爲使用str_replace

str_replace('http://', '', $subject); 
str_replace('https://', '', $subject); 

合併成一個單一的操作如下:

str_replace(array('http://','https://'), '', $urlString); 
+3

這也將刪除任何後續匹配的http(s)://,這可能不是問題 - 但它可能是。例如,如果它在沒有正確的urlencoding的查詢字符串中使用 – aland 2014-04-30 18:31:32

16

更好地利用這一點:

$url = parse_url($url); 
$url = $url['host']; 

echo $url; 

簡單和工程http://https://ftp://和幾乎所有的前綴。

+2

這是正確的答案! – 2015-06-04 09:07:25

+1

最終正確答案! +50 – 2015-07-09 12:44:50

+0

很高興你們喜歡它:) – 2015-07-10 01:10:57

1

要刪除http://domain(或HTTPS),並獲取路徑:

$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str); 
    echo $str; 
0

是的,我認爲str_replace()函數和SUBSTR()更快,比正則表達式更清潔。這是一個安全的快速功能。很容易看到它究竟做了什麼。注意:如果你還想刪除//,則返回substr($ url,7)和substr($ url,8)。

// slash-slash protocol remove https:// or http:// and leave // - if it's not a string starting with https:// or http:// return whatever was passed in 
function universal_http_https_protocol($url) { 
    // Breakout - give back bad passed in value 
    if (empty($url) || !is_string($url)) { 
    return $url; 
    } 

    // starts with http:// 
    if (strlen($url) >= 7 && "http://" === substr($url, 0, 7)) { 
    // slash-slash protocol - remove https: leaving // 
    return substr($url, 5); 
    } 
    // starts with https:// 
    elseif (strlen($url) >= 8 && "https://" === substr($url, 0, 8)) { 
    // slash-slash protocol - remove https: leaving // 
    return substr($url, 6); 
    } 

    // no match, return unchanged string 
    return $url; 
}