PHP Regex从字符串中删除http://

Cas*_*sey 47 php regex

我有完整的URL作为字符串,但我想删除字符串开头的http://以很好地显示URL(例如:www.google.com而不是http://www.google.com)

有人可以帮忙吗?

Sar*_*raz 135

$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com
Run Code Online (Sandbox Code Playgroud)

这将为双方的工作http://https://


Shi*_*dim 23

你根本不需要正则表达式.请改用str_replace.

str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
Run Code Online (Sandbox Code Playgroud)

合并成一个单独的操作如下:

str_replace(array('http://','https://'), '', $urlString);
Run Code Online (Sandbox Code Playgroud)

  • 这也将删除http(s)://的任何后续匹配,这可能不是问题 - 但它可能是.例如,如果它在没有正确的urlencoding的查询字符串中使用 (3认同)

Ift*_*mud 19

更好地利用这个:

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

echo $url;
Run Code Online (Sandbox Code Playgroud)

更简单,适用于http:// https:// ftp://几乎所有前缀.

  • @piersb我不能完全同意你的看法.该代码成功地提供了Casey正在寻找的结果.此外,它是为了一个目的而编写的.如果您想显示路径或查询信息,您当然可以这样做(http://php.net/manual/en/function.parse-url.php).但是,我发现代码存在一个问题.如果我们尝试在不指定协议的情况下解析URL,则会显示错误,这是我现在烦恼的事情:/ (2认同)