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
    
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题