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

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.

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

Use:

preg_match('#/([^/]*)/[^/]*$#', $string, $match);
echo $match[1];

You could also use:

$words = explode('/', $string);
echo $words[count($words)-2];

Regex:

(\w+)(/[^/]+)$

PHP code:

<?php
    $string = "https://ss1.xxx/img/categories_v2/FOOD/fastfood";
    echo preg_replace("@(\w+)(/[^/]+)$@", "food$2", $string);
    $string = "https://ss1.xxx/img/categories_v2/SHOPS/barbershop";
    echo preg_replace("@(\w+)(/[^/]+)$@", "shops$2", $string);
?>