dongyu4908 2014-04-26 11:08
浏览 53
已采纳

在url的最后一部分之前匹配所有内容

I want to match everything in a URL up to the last section.

So I want to match: http://www.test.com/one/two/ in all of the following cases:

http://www.test.com/one/two/three
http://www.test.com/one/two/three/
http://www.test.com/one/two/three/?foo=bar

I'm working in PHP and currently I have /.+\/(?=[^\/]+\/?$)/ this matches everything except the last case but I can't seem to 'not match a forward slash unless it's followed by a question mark' which would seeming sort the problem?

  • 写回答

2条回答 默认 最新

  • dqqvravff05370501 2014-04-26 23:16
    关注

    Here you go, richieahb

    The regex:

    (?m)http://[^/]+(?:/[^/]+)*/(?!\?)(?=[^/
    ]+)
    

    The test (with one more level added)

    <?php
    $string = "http://www.test.com/one/two/three
    http://www.test.com/one/two/three/
    http://www.test.com/one/two/three/four
    http://www.test.com/one/two/three/four/
    http://www.test.com/one/two/three/?foo=barv";
    
    $regex="~(?m)http://[^/]+(?:/[^/]+)*/(?!\?)(?=[^/
    ]+)~";
    
    preg_match_all($regex,$string,$m);
    
    echo "<pre>";
    print_r($m[0]);
    echo "</pre>";
    ?>
    

    The Output:

    Array
    (
        [0] => http://www.test.com/one/two/
        [1] => http://www.test.com/one/two/
        [2] => http://www.test.com/one/two/three/
        [3] => http://www.test.com/one/two/three/
        [4] => http://www.test.com/one/two/
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000