我有完整的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