2012-03-03 222 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; 
}