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

时间:2014-01-11 17:38:19

标签: php regex

我试图在最后/和最后一个/之间提取单词 - 即以下PHP示例中的食物。

  1. $string = https://ss1.xxx/img/categories_v2/FOOD/fastfood(希望将$string替换为food
  2. $string = https://ss1.xxx/img/categories_v2/SHOPS/barbershop(希望将$string替换为shops
  3. 我是regex的新手,并尝试了/[^/]*$ - 但是在最后/之后每次都会返回..任何帮助都会受到赞赏..谢谢!

    我正在使用PHP。

3 个答案:

答案 0 :(得分:1)

使用:

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

你也可以使用:

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

答案 1 :(得分:0)

您可以使用:

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

模式细节:

~            # 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

答案 2 :(得分:0)

正则表达式:

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

PHP代码:

<?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);
?>