PHP regex to remove last matching pattern string

php, preg-match, regex

Solution

You can use the following.

function clean($url) {
   $link = substr(strrchr($url, '/'), 1);
   return substr($url, 0, - strlen($link));
}

echo clean($url);

See `Live demo`

Using regular expression:

$newUrl = preg_replace('~[^/]*$~', '', $url);

See `Live demo`

Problem

I have following URLs ``` http://domain.com/baby/smile/love/index.txt http://domain.com/baby/smile/love/toy.txt http://domain.com/baby/smile/love/car.html and so on... ``` using preg regex, how to remove the file name on the right? I guess it's required to match the first dash starting from the right, how I can do this? So for example if I run something like `$newUrl = preg_match('xxxxxx', '', $url);` or using ``` $newURL = preg_replace(...); ``` The $newUrl variable will only contain ``` http://domain.com/baby/smile/love/ ``` preserving the trailing slash at the end. I was able to do it by using explode(), array_pop(), then implode() to put it back together, just wondering if it 's possible using only regex. Thank you.

Original source