PHP strchr找到最后一次出现的最后一次

时间:2011-03-20 16:56:49

标签: php substr

我使用 strrchr PHP函数与 substr strrpos 在字符串中查找文件名,其中包含完整路径: / p>

  

/images/onepiece.jpg返回   onepiece.jpg

但是现在我需要一个函数来找到最后一个“/”而不是最后一个: /images/anime/onepiece.jpg 返回动漫/ onepiece.jpg /anime/onepiece.jpg 由于 strrchr - 1 不起作用,呵呵呵:),我怎么能实现呢?

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

<?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; ?>" />

4 个答案:

答案 0 :(得分:1)

说实话,使用pathinfodirname函数分解目录路径要容易得多。

例如:

$filename = pathinfo('/images/onepiece.jpg', PATHINFO_BASENAME);
$directory = dirname('/images/onepiece.jpg');

你可能必须混合使用这些来获得你所追求的东西,但它们至少是OS“安全”(即:将处理Linux / Linux和Windows路径样式)。

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

<?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 :(得分:1)

我建议使用explode将路径拆分为其细分:

$segments = explode('/', $path);

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

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

$lastTwoSegments = implode('/', array_slice($segments, -2));

答案 2 :(得分:0)

您需要使用pathinfo功能

pathinfo ($path, PATHINFO_FILENAME );

答案 3 :(得分:0)

老兄,只需制作一个临时字符串来保存你想要找到的字符串。找到最后一个匹配项,将其替换为x之类的内容,然后找到新的最后一个匹配项,即最后一次出现的匹配项。

相关问题