【问题标题】:How can I find a common pattern between 2 urls如何找到 2 个网址之间的共同模式
【发布时间】:2017-01-21 03:42:17
【问题描述】:

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

例如这里有 2 个网址

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

http://example.com/collections/

我要找的是

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

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

【问题讨论】:

    标签: php regex url pattern-matching longest-substring


    【解决方案1】:

    而不是正则表达式,拆分/上的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";
    

    输出:

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

    【讨论】:

    猜你喜欢
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多