从路径获取图像名称


Get image name from path

我正在寻找解决方案:

有一个路径:

$PATH = images/large/Wildebeest-01.jpg
$PATH = images/large/greater-kudu-02.jpg
$PATH = images/large/BLUE-AND-YELLOW-MACAW-08.jpg

我需要的是这个:

"Wildebeest"
"Greater kudu"
"Blue and yellow macaw"

我有第一部分解决方案:

$PATH = $image;
$file = substr(strrchr($PATH, "/"), 1); 
echo  $file;

得到:

  • 角马- 01. - jpg
  • 大捻角羚- 02. jpg
  • 蓝色-和-黄色-金刚鹦鹉- 08. jpg

有人能告诉我,如何从字符串中删除至少"-01.jpg"吗?

谢谢!

试试这个,它使用preg_replace:

$arr = ["Wildebeest-01.jpg", "greater-kudu-02.jpg", "BLUE-AND-YELLOW-MACAW-08.jpg"];
foreach ($arr as $string) {
    $string = preg_replace("/-[^-]*$/", "", $string);
    $string = str_replace("-", " ", $string);
    $string = strtolower($string);
    var_dump($string);
}

获取文件的想法是正确的

$file = substr($PATH,strrpos($PATH, "/"));

然后去掉最后一个-之后的所有内容。

$file = substr($file,0,strrpos($file,'-'));

然后把-变成

$file = str_replace('-',' ',$file);

编辑

如果你不关心将来可能发生的变化,比如更大的数字、不同的文件扩展名等等。你可以简单地做。

$file = substr($file,0,-5);

继续你的解决方案…

$PATH = $image;
$file = substr(strrchr($PATH, "/"), 1); 
$op = preg_replace("/([a-zA-Z-]+).*/", "$1", $file);
$filename = trim( str_replace('-', '', $op); 
echo $filename; // outputs Wildebeest

我的建议:

$array = array();
$array[] = "images/large/Wildebeest-01.jpg";
$array[] = "images/large/greater-kudu-02.jpg";
$array[] = "images/large/BLUE-AND-YELLOW-MACAW-08.jpg";
function get_image_name($path) {
    $file = basename($path);
    if(preg_match("/(.*?)(-[0-9]*){0,1}([.][a-z]{3})/",$file,$reg)) {
        $file = $reg[1];
    }
    $file = ucfirst(strtolower(str_replace("-"," ",$file)));
    return $file;
}
foreach($array as $path) {
    echo "<br>".$path;
    echo " => ".get_image_name($path);
}

输出是:

images/large/Wildebeest-01.jpg => Wildebeest
images/large/greater-kudu-02.jpg => Greater kudu
images/large/BLUE-AND-YELLOW-MACAW-08.jpg => Blue and yellow macaw

还有一个解决方案,使用preg_match():

$getImageName = function ($path) {
   if (preg_match('/(['w'd-_]+)-'d+'.(jpg|jpeg|png|gif)$/i', $path, $matches)) {
       return ucwords(strtolower(str_replace(str_split('-_'), ' ', $matches[1])));
   }
   return false;
};
$paths = array(
   'images/large/Wildebeest-01.jpg',
   'images/large/greater-kudu-02.jpg',
   'images/large/BLUE-AND-YELLOW-MACAW-08.jpg',
);
$names = array_map($getImageName, $paths);

print_r($names);
结果:

Array
(
    [0] => Wildebeest
    [1] => Greater Kudu
    [2] => Blue And Yellow Macaw
)

谢谢大家!根据你的回答,我找到了完美的解决方案:

$filename = pathinfo($PATH);
$filename = $filename['filename'];
$filename = preg_replace("/-[^-]*$/", "", $filename);
$filename= ucfirst(strtolower(str_replace('-',' ',$filename)));
echo $filename;