PHP 字符串格式化(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 个符号?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我说放弃
str
函数,只需explode
、array_slice
和implode
它 =)I say give up on
str
functions, justexplode
,array_slice
andimplode
it =)爆炸然后内爆真的很容易。但如果您想使用字符串函数,则可以使用 strrpos 。
Explode and then implode is real easy. But if you wanted to use a string function instead, you can use strrpos.