简体   繁体   中英

PHP Regular expression replace for url

I need help to replace the last occurance of numeric uri string from my url: For eg I have url strings as:

$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";

from which I want to remove last occurance of "/5" or "/21" or any other number following the last forward slash with empty string and get only:

$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";

Thanks in advance for any help.

Not using preg replace but a simple way :

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

Reference :

http://php.net/manual/en/function.dirname.php

http://php.net/manual/en/function.explode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM