PHP 字符串格式化(substr)

发布于 2024-11-30 06:40:19 字数 826 浏览 2 评论 0原文

我有一个输出路径的函数,这里有一些结果:

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 个符号?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋风の叶未落 2024-12-07 06:40:19

我说放弃 str 函数,只需 explodearray_sliceimplode 它 =)

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

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

$end='/'.implode('/',array_slice(explode('/',$string),-3));
ゝ杯具 2024-12-07 06:40:19

爆炸然后内爆真的很容易。但如果您想使用字符串函数,则可以使用 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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文