Php 正则表达式提取字符最后一次出现和最后第二次出现之间的字符
我试图在最后一个Php 正则表达式提取字符最后一次出现和最后第二次出现之间的字符,php,regex,Php,Regex,我试图在最后一个/和第二个/之间提取单词,即下面的PHP示例中的食物 $string=https://ss1.xxx/img/categories_v2/FOOD/fastfood(要将$string替换为食品) $string=https://ss1.xxx/img/categories_v2/SHOPS/barbershop(要将$string替换为商店) 我对regex是新手,尝试了/[^/]*$——但这是在最后一次/之后返回的所有内容。。任何帮助都将不胜感激。。谢谢 我使用的是PHP。您
/
和第二个/
之间提取单词,即下面的PHP示例中的食物
$string=https://ss1.xxx/img/categories_v2/FOOD/fastfood
(要将$string
替换为食品
)$string=https://ss1.xxx/img/categories_v2/SHOPS/barbershop
(要将$string
替换为商店
)/[^/]*$
——但这是在最后一次/
之后返回的所有内容。。任何帮助都将不胜感激。。谢谢
我使用的是PHP。您可以使用:
$result = preg_replace_callback('~(?<=/)[^/]+(?=/[^/]*$)~', function ($m) {
return strtolower($m[0]); }, $string);
$result=preg\u replace\u回调('~(?使用:
您还可以使用:
$words = explode('/', $string);
echo $words[count($words)-2];
正则表达式:
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);
?>
他想要的是提取,而不是替换。为了理智起见,我还想在选项2中添加一些内容:)
$words = explode('/', $string);
echo $words[count($words)-2];
(\w+)(/[^/]+)$
<?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);
?>