doufuhao8085 2012-08-26 14:39
浏览 99
已采纳

从图像文件名php删除扩展名

I am loading a folder of images into a html page using the following php code.

The problem I am having is that the file name which is being brought through in order to be used as the image caption is showing the file extension.

The part of the code where the name is being pulled is the title='$img'

How do I get it to remove the file extension?

<?php
$string =array();
$filePath='images/schools/';  
$dir = opendir($filePath);
while ($file = readdir($dir)) { 
    if (eregi("\.png",$file) || eregi("\.jpeg",$file) || eregi("\.gif",$file) || eregi("\.jpg",$file) ) { 
        $string[] = $file;
    }
}
while (sizeof($string) != 0) {
    $img = array_pop($string);
    echo "<img src='$filePath$img' title='$img' />";
}

?>

  • 写回答

3条回答 默认 最新

  • dongye9453 2012-08-26 15:00
    关注

    For a "state-of-the-art" OO code, I suggest the following:

    $files = array();
    foreach (new FilesystemIterator('images/schools/') as $file) {
        switch (strtolower($file->getExtension())) {
            case 'gif':
            case 'jpg':
            case 'jpeg':
            case 'png':
                $files[] = $file;
                break;
        }
    }
    
    foreach ($files as $file) {
        echo '<img src="' . htmlentities($file->getPathname()) . '" ' .
             'title="' . htmlentities($file->getBasename('.' . $file->getExtension())) . '" />';
    }
    

    Benefits:

    • You do not use the deprecated ereg() functions anymore.
    • You escape possible special HTML characters using htmlentities().
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部