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


PHP Regex to Remove http:// from string

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

有人能帮忙吗?

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

这将适用于http://https://

您根本不需要正则表达式。请改用str_replace。

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

组合成单个操作如下:

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

更好地使用这个:

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

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

为什么不使用parse_url

删除http://domain(或https)并获取路径:

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

如果您坚持使用RegEx:

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

是的,我认为str_replace()和substr()比regex更快、更干净。这里有一个安全快速的功能。很容易看出它到底做了什么。注意:如果您还想删除//,则返回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;
}
<?php
    // (PHP 4, PHP 5, PHP 7)
    // preg_replace — Perform a regular expression search and replace
$array = [
    'https://lemon-kiwi.co',
    'http://lemon-kiwi.co',
    'lemon-kiwi.co',
    'www.lemon-kiwi.co',
];
foreach( $array as $value ){
    $url = preg_replace("(^https?://)", "", $value );
}

此代码输出:

lemon-kiwi.co
lemon-kiwi.co
lemon-kiwi.co
www.lemon-kiwi.co

请参阅文档PHP preg_replace