我在变量中有一个网址。
<?php
$a='www.example.com';
?>
我有另一个变量,如下所示
<?php
$b='example.com';
?>
我可以通过什么方式检查$b和$a是否相同。我的意思是即使$b中的网址像
'example.com/test','example.com/test.html','www.example.com/example.html'
在这种情况下,我需要检查$b是否等于$a。如果域名更改时像example.net/example.org
,则应返回 false。我与strpos
和strcmp
核实.但是我没有发现这是检查网址的正确方法。在这种情况下,我可以使用什么功能来检查$b是否与$a相似?
您可以使用
parse_url
来解析URL并获取根域,如下所示:
- 将
http://
添加到 URL(如果尚不存在) - 使用常量获取 URL 的主机名部分
PHP_URL_HOST
- 用点
explode
网址 (.
) - 使用
array_slice
获取数组的最后两个块 - 内爆结果数组以获取根域
我做的一个小函数(这是我自己在这里回答的修改版本):
function getRootDomain($url)
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
$domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
return $domain;
}
测试用例:
$a = 'http://example.com';
$urls = array(
'example.com/test',
'example.com/test.html',
'www.example.com/example.html',
'example.net/foobar',
'example.org/bar'
);
foreach ($urls as $url) {
if(getRootDomain($url) == getRootDomain($a)) {
echo "Root domain is the same'n";
}
else {
echo "Not same'n";
}
}
输出:
Root domain is the same
Root domain is the same
Root domain is the same
Not same
Not same
注意:此解决方案并非万无一失,对于 example.co.uk
等网址可能会失败,您可能需要进行其他检查以确保不会发生这种情况。
演示!
您可以使用
parse_url
来完成繁重的工作,然后按点拆分主机名,检查最后两个元素是否相同:
$url1 = parse_url($url1);
$url2 = parse_url($url2);
$host_parts1 = explode(".", $url1["host"]);
$host_parts2 = explode(".", $url2["host"]);
if ($host_parts1[count($host_parts1)-1] == $host_parts2[count($host_parts2)-1] &&
($host_parts1[count($host_parts1)-2] == $host_parts2[count($host_parts2)-2]) {
echo "match";
} else {
echo "no match";
}
我认为
这个答案可以提供帮助: 搜索部分字符串 PHP
因为这些 URL 无论如何都只是字符串