I need to strip the last part of a URL.
example: http://www.example.com/dir1/dir2/greetz.html
needed result: http://www.example.com/dir1/dir2
I wanted to do this by using explode '/', only I don't know how many
times '/' occurs in the URL so I want to start 'explode' from the
right instead of the left (so the 'first explode' is the 'greetz.html'
part)
I’m almost sure it's possible, just can’t remember or find how to do
this, can someone please help me out?
Thanks in advance,
Grtz
Bob
Sometimes I’m just searing in the wrong direction...
thanks
Bob
Indeed, that would be the easier approach. However, in case you're
curious about the explode() question, I thought I'd follow-up.
I don't think you can explictly explode() from right to left, but you
can reverse the string passed to explode():
$tokens = explode(' ', strrev($s));
--
Curtis
$email = str_replace('sig.invalid', 'gmail.com', $from);
You can also do
substr($string, strrpos($string, '/') + 1);
I was indeed still curious about a solution for the first approach
(start explode() from the right). I was almost sure I did use
someting
like that in de past so I went looking in some of my older php
scripts
and didn't found exactly where I was looking for, the approach I used
about a year ago was using 'end' function (http://nl.php.net/end),
example
$url = 'http://www.example.com/dir1/dir2/greetz.html ';
echo end(explode("/", $url)); // greetz.html
Thanks again,
Bob
$string = "http://in.php.net/manual/en/function.strrev.php";
print substr($string, 0, (strrpos($string, '/')+1));
Output : http://in.php.net/manual/en/
dirname() works quite well:
echo dirname('http://www.example.com/dir1/dir2/greetz.html') . "\n";
echo dirname('http://www.example.com/dir1/dir2/') . "\n";
echo dirname('http://www.example.com/dir1/dir2') . "\n";
... prints:
http://www.example.com/dir1/dir2
http://www.example.com/dir1
http://www.example.com/dir1
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
He wants the LAST piece, so as I posted earlier:
substr($string, (strrpos($string, '/')+1));
Pliease ignore my last post. He actually DID want the front piece, not
the last piece.
If you apply that to, say, "cat dog chair", you'd get array('riahc',
'god', 'tac').
Instead, just try:
$tokens = array_reverse(explode(YOUR_DELIMITER, $string)); //
YOUR_DELIMITER is '/' in the original problem.
Or, if you were interested in keeping everything but the last token:
$tokens = explode(YOUR_DELIMITER, $string);
array_pop($tokens); // used in a void context to throw the end away
$string = implode(YOUR_DELMITER, $tokens);
But in this particular case, dirname() is a handy solution, and the
substr solutions are neater and quicker.
Absolutely right, thanks for catching that. No idea what I was
thinking.