0

我想在 PHP 中找到 2 个 URL 之间的共同模式。我已经玩过https://gist.github.com/chrisbloom7/1021218但这在找到最长的匹配时停止,而不考虑 URL 中存在的通配符。

例如这里有 2 个 URL

如果我在这些上运行函数,我的常见模式是

http://example.com/collections/

我正在寻找的是

http://example.com/collections/*/products/

有谁知道我可以如何调整代码以使其工作,或者有更好的方法吗?

4

1 回答 1

1

而不是正则表达式,拆分网址/然后比较数组的每个元素,然后重新组合网址:

$url1 = 'http://example.com/collections/dresses/products/foo/dress.html';
$url2 = 'http://example.com/collections/shoes/products/shoe.html';

$part1 = explode('/', $url1);
$part2 = explode('/', $url2);

$common = array();
$len = count($part1);
if (count($part2) < $len) $len = count($part2);

for ($i = 0; $i < $len-1; $i++) {
    if ($part1[$i] == $part2[$i]) {
        $common[] = $part1[$i];
    } else {
        $common[] = '*';
    }
}
$out = implode('/', $common);
echo "$out\n";

输出:

http://example.com/collections/*/products
于 2017-01-21T11:20:42.807 回答