PHP字符串格式化(substr)


PHP string formatting (substr)

我有一个输出路径的函数,下面是一些结果:

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

除了文件名和两个父目录外,我想从这些目录中删除所有内容,所以上面的内容看起来像:

/2021/12/file.txt
/2016/16/file.txt
/2001/22/file.txt
/20012/06/file.txt
所以基本上我必须从末尾找到第三个"/"并显示它和后面的所有内容。

我不太懂PHP,但我想这是很容易实现与substr(), stripos()和strlen(),所以:

$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;

这是正确的方法,或者可能有另一个内置的函数,搜索第n个字符在一个字符串?

我说放弃str函数,只考虑explode, array_sliceimplode它=)

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

爆炸然后内爆真的很容易。但是如果你想使用字符串函数,你可以使用strpos .

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