我有一个包含相对路径的图像文件数组,如下所示:gallery/painting/some_image_name.jpg
。我将此数组传递到foreach
循环,该循环将路径打印到<img>
的源。
从这样的行中提取名称的安全可靠方法是什么?
gallery/painting/some_image_name.jpg
&gt;到&gt; 某些图片名称
答案 0 :(得分:4)
basename($ path,“.jpg”)给出some_image_name,然后你可以用空格替换_。
str_replace('_', ' ', basename($path, ".jpg"));
答案 1 :(得分:1)
function ShowFileName($filepath)
{
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];
#split the string by the literal dot in the filename
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
#get the last dot position
$lastdot = $pattern[count($pattern)-1][1];
#now extract the filename using the basename function
$filename = basename(substr($string, 0, $lastdot-1));
#return the filename part
return $filename;
}
答案 2 :(得分:0)
$actual_name = str_replace('_', ' ', basename($input));
答案 3 :(得分:0)
如何使用pathinfo
提取构成文件名的部分?
例如:
$name = 'gallery/painting/some_image_name.jpg';
$parts = pathinfo($name);
var_dump($parts);
哪能得到你:
array
'dirname' => string 'gallery/painting' (length=16)
'basename' => string 'some_image_name.jpg' (length=19)
'extension' => string 'jpg' (length=3)
'filename' => string 'some_image_name' (length=15)
然后,您可以使用str_replace
将_替换为空格:
$name2 = str_replace('_', ' ', $parts['filename']);
var_dump($name2);
你会得到:
string 'some image name' (length=15)
答案 4 :(得分:0)
路径信息和str_replace。
$path = 'gallery/painting/some_image_name.jpg';
$r = pathinfo($path, PATHINFO_FILENAME);
echo str_replace('_', ' '. $r['filename']);