1

I have a function that outputs a path, here are some results:

http://server.com/subdirectory/subdiretory/2021/12/file.txt
http://server.com/subdirectory/subdiretory/something/else/2016/16/file.txt
http://server.com/subdirectory/subdiretory/2001/22/file.txt
C:\totalmess/mess\mess/2012/06/file.txt

I want to cut everything from these excepting filename and two parent directories, so the ones above will look like:

/2021/12/file.txt
/2016/16/file.txt
/2001/22/file.txt
/20012/06/file.txt

So basically I have to find the third "/" from the end and display it with everything afterwards.

I don't know PHP too good, but I guess this is pretty easy to achieve with substr(), stripos() and strlen(), so:

$string ="http://server.com/subdirectory/subdiretory/2001/22/file.txt"
$end = strlen($string);
$slash = // How to get the right slash using stripos()?
$output = substr($string, $slash, $end);
echo $output;

Is this the right way of doing this, or maybe there's another in-built function that searches for -nth symbols within a string?

2 Answers 2

3

I say give up on str functions, just explode, array_slice and implode it =)

$end='/'.implode('/',array_slice(explode('/',$string),-3));
Sign up to request clarification or add additional context in comments.

2 Comments

You'll, of course, need to re-implode if you do this to get a string back. (Also, you don't need to pass the 3 length argument; array_slice will include up to the end of the array by default.)
@John, thanks for the note about unnecessary param, i had actually caught the implode before your note ;)
-1

Explode and then implode is real easy. But if you wanted to use a string function instead, you can use strrpos.

$string ="http://server.com/subdirectory/subdiretory/2001/22/file.txt"
$slash = strrpos( $string, '/', -3 ); // -3 should be the correct offset.
$subbed = substr( $string, $slash ); //length doesn't need to be specified.

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.