Php 如何在两个URL之间找到通用模式

Php 如何在两个URL之间找到通用模式,php,regex,url,pattern-matching,longest-substring,Php,Regex,Url,Pattern Matching,Longest Substring,我想找到PHP中两个URL之间的通用模式。 我已经尝试过了,但这仅仅是为了找到最长的匹配,而没有考虑URL中存在的通配符 e、 这里有两个URL 如果我在这些上运行函数,我的常见模式是 http://example.com/collections/ 我要找的是 http://example.com/collections/*/products/ http://example.com/collections/*/产品/ 有人知道我如何调整代码以使其正常工作吗?或者有更好的方法吗?在/上拆分

我想找到PHP中两个URL之间的通用模式。 我已经尝试过了,但这仅仅是为了找到最长的匹配,而没有考虑URL中存在的通配符

e、 这里有两个URL

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

http://example.com/collections/ 我要找的是

http://example.com/collections/*/products/ http://example.com/collections/*/产品/
有人知道我如何调整代码以使其正常工作吗?或者有更好的方法吗?

/
上拆分url,然后比较数组的每个元素,然后重新组合url:

$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";

精彩的!对未显式包含在URL中的索引页进行了一个小的调整,例如if(substr($out,-1)!=“*”){$out=$out./*”;}
http://example.com/collections/*/products