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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧