dsam70528 2018-08-21 20:09
浏览 16
已采纳

如果url包含某个目录,则返回url的结尾

I need to search thru a sql file and find the filename (the end of the url) where the url contains /assets/

Example url:

https://www.example.com/assets/screenshots/this-is-an-example/2016-12-20_15-42-29.png

It has /assets/ in it, so I want to get the last part of the url, being:

2016-12-20_15-42-29.png

Another example:

https://www.example.com/images/screenshots/this-is-an-example/2016-12-20_15-42-29.png

Nothing would return because /assets/ was not found.

*The number of directories deep it goes will be different, so it could be /assets/dir1/dir2/filename.jpg, and the next could be /assets/dir1/dir2/dir3/dir4/filename.jpg

Hoping this can be accomplished using regular expression.

  • 写回答

3条回答 默认 最新

  • dongrong9053 2018-08-21 20:44
    关注

    You may use the following regex:

    ^(?=.*\/assets\/).*\/\K.*$
    
    • ^ Assert position beginning of string.
    • (?=.*\/assets\/) Positive lookahead to ensure that /assets/ substring is present in the string.
    • .* Match anything greedily.
    • \/ Match the last /.
    • \K Reset operator, resets match.
    • .*$ Match anything until end of string $.

    You can try it here.


    Php snippet:

    <?php
    
    $url = 'https://w...content-available-to-author-only...e.com/assets/screenshots/this-is-an-example/2016-12-20_15-42-29.png';
    preg_match('/^(?=.*\/assets\/).*\/\K.*$/',$url,$matches);
    
    print_r($matches[0]);
    

    Prints:

    2016-12-20_15-42-29.png
    

    You can try it here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 simulink单相桥式整流电路
  • ¥35 问问51单片机流水灯的代码该怎么写
  • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
  • ¥15 stata webuse报错
  • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
  • ¥15 如何利用AI去除图片中的竹架子
  • ¥15 python 写个基金爬取的代码,自动卖出功能
  • ¥15 Linux系统启动不起来
  • ¥15 为什么运行仿真数码管不亮(语言-c语言)
  • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导