4

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.

1
  • If you need regex free solution , try this echo substr($link1,0,strrpos($link1,'/')+1); Commented Dec 4, 2013 at 6:10

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this preg_replace is exactly what I was looking for.
3
<?php
$str = 'http://domain.com/baby/smile/love/index.txt';

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

Output:

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

Comments

1

This should work:

$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/
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.