0

我在变量中有一个 url。

<?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。我检查了strposstrcmp。但是我没有发现这是检查url的正确方法。我可以使用什么函数来检查这种情况下的$b是否类似于$a?

4

3 回答 3

1

您可以使用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";
}
于 2013-09-28T14:59:01.333 回答
1

您可以parse_url用于解析 URL 并获取根域,如下所示:

  • http://如果不存在,则添加到 URL
  • PHP_URL_HOST使用常量获取 URL 的主机名部分
  • explode一个点 ( .)的 URL
  • 使用获取数组的最后两个块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

注意:此解决方案并非万无一失,并且对于诸如此类的 URL 可能会失败example.co.uk,您可能需要进行额外检查以确保不会发生这种情况。

演示!

于 2013-09-28T15:06:38.027 回答
0

我认为这个答案会有所帮助:Searching partial strings PHP

因为这些 URL 无论如何都只是字符串

于 2013-09-28T14:52:39.443 回答