gpt4 book ai didi

php - 在可能不包含协议(protocol)的字符串上运行 parse_url()

转载 作者:行者123 更新时间:2023-12-04 04:36:56 24 4
gpt4 key购买 nike

我正在尝试从用户输入的 URL 字符串中获取域名和 TLD(无子域),该字符串可能有也可能没有协议(protocol)、目录、子域、文件名等。

换句话说,给定以下任何一项:

example.com
www.example.com
sub.example.com
example.com/whatever/hey.html
http://example.com
https://subdomain.example.com
ftp://example.com/whatever/hey.html

我应该总是以: example.com 结尾.

现在这就是我正在做的事情:
$hostParts = explode('.', parse_url($URL, PHP_URL_HOST));
$tld = array_pop($hostParts);
$domain = array_pop($hostParts);
$domain = $domain . "." . $tld;

但是,如果提供的 URL 没有协议(protocol),它就会中断。为什么是 parse_url在这种情况下无法获得主机?

最佳答案

根据定义,URL 包含协议(protocol)或方案。检查//如果不存在,则将//添加到字符串。这在 PHP < 5.4.7 中可能有所不同,因此如果没有协议(protocol),可以添加 http://。

关于php - 在可能不包含协议(protocol)的字符串上运行 parse_url(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com