📜  从链接 php 中删除 http https(1)

📅  最后修改于: 2023-12-03 14:49:29.007000             🧑  作者: Mango

从链接 php 中删除 http https

在 PHP 中,我们经常需要处理链接,有时候我们需要删除链接中的 "http://" 或 "https://" 前缀。本文将为程序员介绍几种方法来实现这个目标。

方法一:使用 str_replace() 函数
$url = "http://www.example.com";
$strippedUrl = str_replace(array("http://", "https://"), "", $url);

echo $strippedUrl;  // 输出 "www.example.com"

使用 str_replace() 函数,我们可以将 "http://" 和 "https://" 替换为空字符串来实现删除的效果。

方法二:使用 preg_replace() 函数
$url = "http://www.example.com";
$strippedUrl = preg_replace("~^(?:https?://)?~i", "", $url);

echo $strippedUrl;  // 输出 "www.example.com"

preg_replace() 函数可以使用正则表达式替换字符串。上述代码中,我们使用了正则表达式 ~^(?:https?://)?~i 来匹配 "http://" 或 "https://",并将其替换为空字符串。

方法三:使用 parse_url() 函数
$url = "http://www.example.com";
$components = parse_url($url);

$strippedUrl = $components['host'];

echo $strippedUrl;  // 输出 "www.example.com"

parse_url() 函数可以解析一个 URL 并返回其组成部分的关联数组。我们可以直接获取 host 部分来实现删除 "http://" 或 "https://" 的效果。

方法四:使用 substr() 函数
$url = "http://www.example.com";
$strippedUrl = substr($url, strpos($url, "://") + 3);

echo $strippedUrl;  // 输出 "www.example.com"

使用 substr() 函数和 strpos() 函数,我们可以找到第一个冒号和斜杠之后的位置,然后使用 substr() 函数截取字符串,从而实现删除 "http://" 或 "https://" 的效果。

以上就是几种常用的方法来删除链接中的 "http://" 或 "https://" 前缀的介绍。你可以根据自己的需求选择适合的方法来处理链接。希望对你有帮助!