我使用带有、substr、和strrpos的strrchr PHP函数在字符串中查找文件名,其完整路径如下:
/图像/onpiece.jpg返回onepiece.jpg
但是现在我需要一个函数,不是最后一个"/“,而是最后一个:/images/anime/onepiece.jpg返回anime/onepiece.jpg或/anime/onepiece.jpg,而strrchr - 1不起作用,呵呵:),我怎么能做到这一点?
使用pathinfo()解决问题,就像@middaparka和@Shakti说的那样,我改变了从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; ?>" />发布于 2011-03-20 17:01:35
老实说,使用帕辛弗或脏名函数分解目录路径要容易得多。
例如:
$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;
?>发布于 2011-03-20 17:46:24
我建议使用explode将路径分成几个部分:
$segments = explode('/', $path);然后可以使用$segments[count($segments)-1]获取最后一个路径段。
对于最后两个段,您可以使用array_slice和implode将它们组合在一起:
$lastTwoSegments = implode('/', array_slice($segments, -2));发布于 2011-03-20 17:01:11
您需要使用帕辛弗函数
pathinfo ($path, PATHINFO_FILENAME );https://stackoverflow.com/questions/5369949
复制相似问题