首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP strrchr查找最后一个而不是最后一个

PHP strrchr查找最后一个而不是最后一个
EN

Stack Overflow用户
提问于 2011-03-20 16:56:48
回答 4查看 1.2K关注 0票数 0

我使用带有、substr、strrposstrrchr PHP函数在字符串中查找文件名,其完整路径如下:

/图像/onpiece.jpg返回onepiece.jpg

但是现在我需要一个函数,不是最后一个"/“,而是最后一个:/images/anime/onepiece.jpg返回anime/onepiece.jpg/anime/onepiece.jpg,而strrchr - 1不起作用,呵呵:),我怎么能做到这一点?

使用pathinfo()解决问题,就像@middaparka和@Shakti说的那样,我改变了从MySQL数据库获取图像字符串的方式。现在它可以有子文件夹,这是我最初的意图。

代码语言:javascript
复制
<?php
/*
 * pathinfo() parameters:
 * PATHINFO_DIRNAME = 1
 * PATHINFO_BASENAME = 2
 * PATHINFO_EXTENSION = 4
 * PATHINFO_FILENAME = 8
 * */
    $slash = '/';
    $mainpath = 'store/image/';
    $thumbspath = 'cache/';
    $path = $imgsrow->photo; //gets the string containing the partial path and the name of the file from the database
    $dirname = pathinfo($path, 1); //gets the partial directory string
    $basename = pathinfo($path, 2); //gets the name of the file with the extension
    $extension = pathinfo($path, 4); //gets the extension of the file
    $filename = pathinfo($path, 8); //gets the name of the file
    $dims = '-100x100.'; //string of size of the file to append to the file name
    $image = $mainpath . $path; //mainpath + path is the full string for the original/full size file
    $thumbs = $mainpath . $thumbspath . $dirname . $slash . $filename . $dims . $extension; //string to point to the thumb image generated from the full size file
?>
    <img src="<?= $thumbs; ?>" width="100" height="100" alt="<?= $row->description; ?>" />
    <br />
    <img src="<?= $image; ?>" width="500" height="500" alt="<?= $row->description; ?>" />
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-03-20 17:01:35

老实说,使用帕辛弗脏名函数分解目录路径要容易得多。

例如:

代码语言:javascript
复制
$filename = pathinfo('/images/onepiece.jpg', PATHINFO_BASENAME);
$directory = dirname('/images/onepiece.jpg');

您可能需要使用这些方法来获得您想要的结果,但它们至少是OS“安全”的(即:将处理Linux/Linux和Windows路径样式)。

就您所遇到的具体问题而言,您应该能够使用以下跨平台解决方案来获得所需的东西:

代码语言:javascript
复制
<?php
    $sourcePath = '/images/anime/onepiece.jpg';

    $filename = pathinfo($sourcePath, PATHINFO_BASENAME);
    $directories = explode(DIRECTORY_SEPARATOR, pathinfo($sourcePath, PATHINFO_DIRNAME));

    echo $directories[count($directories) -1] . DIRECTORY_SEPARATOR . $filename;
?>
票数 1
EN

Stack Overflow用户

发布于 2011-03-20 17:46:24

我建议使用explode将路径分成几个部分:

代码语言:javascript
复制
$segments = explode('/', $path);

然后可以使用$segments[count($segments)-1]获取最后一个路径段。

对于最后两个段,您可以使用array_sliceimplode将它们组合在一起:

代码语言:javascript
复制
$lastTwoSegments = implode('/', array_slice($segments, -2));
票数 1
EN

Stack Overflow用户

发布于 2011-03-20 17:01:11

您需要使用帕辛弗函数

代码语言:javascript
复制
pathinfo ($path, PATHINFO_FILENAME );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5369949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档