url的PHP正则表达式替换

url的PHP正则表达式替换,php,regex,Php,Regex,我需要帮助来替换url中最后出现的数值uri字符串: 例如,我有如下url字符串: $url1 = "http://localhost/mystore/electronics/company/5-mobile/5"; $url2 = "http://localhost/mystore/electronics/company/5-mobile/21"; $url3 = "http://localhost/mystore/electronics/company/5-mobile"; 我想从中删除最

我需要帮助来替换url中最后出现的数值uri字符串: 例如,我有如下url字符串:

$url1 = "http://localhost/mystore/electronics/company/5-mobile/5";
$url2 = "http://localhost/mystore/electronics/company/5-mobile/21";
$url3 = "http://localhost/mystore/electronics/company/5-mobile";
我想从中删除最后出现的“/5”或“/21”或最后一个带空字符串的正斜杠后面的任何其他数字,并仅获取:

$url1_after_preg_replace = "http://localhost/mystore/electronics/company/5-mobile";
$url2_after_preg_replace = "http://localhost/mystore/electronics/company/5-mobile";
$url3_after_preg_replace = "http://localhost/mystore/electronics/company/5-mobile";

提前感谢您的帮助。

不使用preg replace,而是使用一种简单的方法:

if(explode(dirname($url1),$url1)[1] != "/5-mobile") {
    $url1_after_preg_replace = dirname($url1);
}
参考:


thnks。它只能部分解决我的问题。我忘了提到url也可以是:“/5”部分可能根本不存在。