duanlang1196 2014-01-11 17:38
浏览 564

正则表达式在最后一次和最后一次出现的字符之间提取字符

i am trying to extract the word in between the last / and the second last / - i.e. food in the following PHP example.

  1. $string = https://ss1.xxx/img/categories_v2/FOOD/fastfood (would like to replace $string to food)
  2. $string = https://ss1.xxx/img/categories_v2/SHOPS/barbershop (would like to replace $string to shops)

I am new to regex and tried /[^/]*$ - however that is returning everying after the last /.. any help would be appreciated.. thanks!

I am using PHP.

  • 写回答

3条回答

  • dongmi4035 2014-01-11 17:41
    关注

    You can use this:

    $result = preg_replace_callback('~(?<=/)[^/]+(?=/[^/]*$)~', function ($m) {
      return strtolower($m[0]); }, $string);
    

    Pattern details:

    ~            # pattern delimiter
    (?<=/)       # zero width assertion (lookbehind): preceded by /
    [^/]+        # all characters except / one or more times
    (?=/[^/]*$)  # zero width assertion (lookahead): followed by /,
                 # all that is not a / zero or more times, and the end of the string
    ~            # pattern delimiter
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决