2014-01-08 45 views
0

考虑到我从一个文件夹(g-images /)创建一个图库并使用文件名作为标题的工作代码,我该如何从这些标题中排除除* .jpg之外的其他文件扩展名(即*。 png,* .gif)?如何从文件夹中使用文件名作为PHP库的标题时排除文件扩展名?

此刻被删除的唯一扩展名是* .jpg。如果它是任何其他扩展它保存为标题对图像的一部分...

HELP,总新手在这里:-)

<?php 
    $imglist = array(); 
    $img_folder = "g-images/"; 

    //use the directory class 
    $imgs = dir($img_folder); 

    //read all files from the directory, checks if are images and adds them to a list 
    while ($file = $imgs->read()) { 
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)){ 
    $imglist[] = $file; 
    } 
} 
closedir($imgs->handle); 

//display image 
foreach($imglist as $image) { 
echo '<li><a href="'.$img_folder.$image.'" target="zoomed"><img src="timthumb.php?src='.$img_folder.$image.'&a=r&h=260" />'; 
echo '<p>'.str_replace('.jpg', ' ', str_replace('name', 'Name', $image)).'</p></a></li>'; 
} 
?> 
+0

感谢大家的帮助!我真的很感激,欢呼! :-) – kcullen

回答

0

尝试更换这行:

$imglist[] = $file; 

$imglist[] = substr($file, 0, strrpos($file, '.')); 

文件名使它进入前阵这将砍掉文件扩展名,并会与任何推广工作(你会不会继续增加扩展到一个数组,如果,例如,在未来要支持* .TIFF)

更新

您可以通过数组跟踪的文件扩展名的条目阵列本身:

$position = strrpos($file, '.'); 
$imglist[] = array( 
    'filename' => substr($file, 0, $pos), 
    'extension' => substr($file, $pos), 
); 

此外,请参阅this question以更好地确定文件是否为图像。

+0

OP使用'$ imglist'中的条目来创建文件路径。在创建路径之前,您无法删除扩展名。 –

+0

谢谢,我的答案更新了 –

0

内,您的foreach循环,你可以做以下

foreach($imglist as $image) { 
    echo '<li><a href="'.$img_folder.$image.'" target="zoomed"><img src="timthumb.php?src='.$img_folder.$image.'&a=r&h=260" />'; 
    // Explode the image name 
    $arr = explode('.', $image); 
    if(isset($arr[0]){ 
     // Get the first element of the array 
     $imageName = $arr[0]; 
     echo '<p>'.str_replace('name', 'Name', $imageName).'</p></a></li>'; 
    } 
} 
+0

如果我命名一个文件,该怎么办:my.image.file.jpg? –

0

一个PHP招完成,这是爆炸()的名称,将其划分在.是。然后,我们只是array_pop()扩展关闭,爆它放回一个字符串:

$file_array = explode(".",$image); 
$extension = array_pop($file_array); 
$filename = implode($file_array); 
$filename = ucfirst($filename); 
var_dump($filename); 

我这个代码

str_replace('name', 'Name', $image) 

你想利用字符串承担?你的代码所做的是查找文本字符串“名”,如果找到,使用该文本字符串“名称” ...更换为了利用你想串$标题的第一个字母:

$capitalizedTitle = ucfirst($title); 
相关问题