开发者

PHP string formatting (substr)

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:

开发者_JS百科$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?


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

$end='/'.implode('/',array_slice(explode('/',$string),-3));


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜