PHP regular expression to remove last line of matching pattern

I have the 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 this should match the first dash starting on the right, how can I do this?

So for example, if I run something like

$newUrl = preg_match('xxxxxx', '', $url);

or using

$newURL = preg_replace(...);

The variable $ newUrl will contain

http://domain.com/baby/smile/love/

keeping the trailing slash at the end. I was able to do this using the functions explode (), array_pop (), then implode () to get it back, just wondering if it is possible to use only regular expression.

Thanks.

+4
source share
3 answers

You can use the following.

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

echo clean($url);

Cm. Live demo

Using regex:

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

Cm. Live demo

+4
<?php
$str = 'http://domain.com/baby/smile/love/index.txt';

$str = preg_replace('/(.*\/).*/', '$1', $str);
print $str;

:

http://domain.com/baby/smile/love/
+3

:

$s = 'http://domain.com/baby/smile/love/index.txt';

if (preg_match_all('~^.+?/(?!.*?/)~', $s, $matches))
        print_r ( $matches[0] );

OUTPU:

Array
(
    [0] => http://domain.com/baby/smile/love/
)
+1

All Articles