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

我想在最后的 / </ code>和第二个之间提取单词< 代码> / </ code> - 即以下PHP示例中的食物。</ p>


  1. $ string = https://ss1.xxx/img/categories_v2/ FOOD / fastfood </ code>(想将 $ string </ code>替换为 food </ code>)</ li>
  2. $ string = https:// ss1.xxx/img/categories_v2/SHOPS/barbershop </ code>(想将 $ string </ code>替换为商店</ code>)</ li>
    </ ol> \ n

    我是regex的新手并且尝试了 / [^ /] * $ </ code> - 但是在最后的 / </ code>之后每次都会返回..任何帮助都会是 感谢...谢谢!</ p>

    我正在使用PHP。</ p>
    </ div>

展开原文

原文

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个回答



使用:</ p>

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

你也可以使用:</ p >

  $ words = explode('/',$ string); 
echo $ words [count($ words)-2];
</ code> </ pre>
</ DIV>

展开原文

原文

Use:

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

You could also use:

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

doutui6644
doutui6644 我还会在选项2中的某处抛出parse_url($ string,PHP_URL_PATH)以获得理智:)
6 年多之前 回复

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

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
dongmiyu8979
dongmiyu8979 他想要提取而不是取代。
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问