我有完整的URL作爲字符串,但我想刪除在字符串開頭的http://以很好地顯示URL(例如:www.google.com,而不是http://www.google.com)PHP的正則表達式來刪除http://字符串
有人可以幫忙嗎?
我有完整的URL作爲字符串,但我想刪除在字符串開頭的http://以很好地顯示URL(例如:www.google.com,而不是http://www.google.com)PHP的正則表達式來刪除http://字符串
有人可以幫忙嗎?
如果你堅持使用正則表達式上:
preg_match("/^(https?:\/\/)?(.+)$/", $input, $matches);
$url = $matches[0][2];
爲了完整起見,我會在http後添加's?'。是的,我知道這不是他的問題。 。 。 :)) – 2012-03-03 21:10:45
好主意,更新。 – Overv 2012-03-03 21:12:20
工作,爲什麼不使用parse_url
呢?
根本不需要正則表達式。改爲使用str_replace。
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
合併成一個單一的操作如下:
str_replace(array('http://','https://'), '', $urlString);
這也將刪除任何後續匹配的http(s)://,這可能不是問題 - 但它可能是。例如,如果它在沒有正確的urlencoding的查詢字符串中使用 – aland 2014-04-30 18:31:32
更好地利用這一點:
$url = parse_url($url);
$url = $url['host'];
echo $url;
簡單和工程http://
https://
ftp://
和幾乎所有的前綴。
這是正確的答案! – 2015-06-04 09:07:25
最終正確答案! +50 – 2015-07-09 12:44:50
很高興你們喜歡它:) – 2015-07-10 01:10:57
要刪除http://domain(或HTTPS),並獲取路徑:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;
是的,我認爲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;
}
爲什麼你需要一個正則表達式?爲什麼不只是刪除前7個字符? – 2012-03-03 21:08:01
檢查這一個:http://stackoverflow.com/questions/4875085/php-remove-http-from-link-title – stefandoorn 2012-03-03 21:09:28
@OliCharlesworth:它可以是8個字符以及'https://' – Sarfraz 2012-03-03 21:11:20