Php 从路径中获取图像名称
我正在为此搜索解决方案: 我有一条路:Php 从路径中获取图像名称,php,string,Php,String,我正在为此搜索解决方案: 我有一条路: $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 = su
$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;
$filename = pathinfo($PATH);
$filename = $filename['filename'];
$filename = preg_replace("/-[^-]*$/", "", $filename);
$filename= ucfirst(strtolower(str_replace('-',' ',$filename)));
echo $filename;
这给了我:
- 牛羚-01.jpg
- greater-kudu-02.jpg
- 蓝黄金刚鹦鹉-08.jpg
谢谢 获取文件的想法是正确的
$file = substr($PATH,strrpos($PATH, "/"));
然后,在最后一次-
之后,要想摆脱一切,只需执行以下操作
$file = substr($file,0,strrpos($file,'-'));
$file = substr($file,0,-5);
然后将-
转换为
$file = str_replace('-',' ',$file);
编辑
如果你不关心将来可能发生的变化,比如更大的数字、不同的文件扩展名等等。你可以简单地做
$file = substr($file,0,strrpos($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);
}
另一个解决方案是使用preg_match(): 结果:
Array
(
[0] => Wildebeest
[1] => Greater Kudu
[2] => Blue And Yellow Macaw
)
谢谢大家!根据您的回答,我找到了完美的解决方案:
$PATH = $image;
$file = substr(strrchr($PATH, "/"), 1);
echo $file;
$filename = pathinfo($PATH);
$filename = $filename['filename'];
$filename = preg_replace("/-[^-]*$/", "", $filename);
$filename= ucfirst(strtolower(str_replace('-',' ',$filename)));
echo $filename;
substr($filename,-5);
$PATH
>的值是多少?substr($filename,-5)>>>>>我不需要字符串的最后一部分,这不是解决方案,我需要删除最后一部分警告:substr()预期参数2很长,字符串以D:\PHP\u SOURCE\tst.PHP
给出测试答案,而不仅仅是猜测them@RiggsFolly哎呀,打字错误。本应键入strrpos
,但出于某种原因键入strrchr
。谢谢你的提示。@RiggsFolly这就是他们的OP中所显示的:“我需要的是这样的:”如果文件名使用下划线而不是破折号来分隔不同的单词,我会在strtolower()中执行此操作:str_replace(str_split('-"'),'$filename);由于str_replace接受一次替换多个字符的数组,并且str_split()将字符串拆分为数组元素,因此一举两得。