PhP Search Directory By File Extension

三世轮回 提交于 2021-02-04 21:51:55

问题


I have a script and a function in it gets every file in that folder. How can I edit this code to make it so it only gets .png files?

public function GetPreviews($category)
    {
        $directories = glob("assets/preview/$category/*");
        $directory = array();
        foreach($directories as $directories)
        {
            $directory[] = str_replace("assets/preview/$category/", "", $directories);   
        }
        return $directory;      
    }

回答1:


add .png to glob("assets/preview/$category/*.png");

public function GetPreviews($category)
    {
        $directories = glob("assets/preview/$category/*.png");
        $directory = array();
        foreach($directories as $directories)
        {
            $directory[] = str_replace("assets/preview/$category/", "", $directories);   
        }
        return $directory;      
    }



回答2:


Since you are using glob() - just add .png after the last *

Like so:

public function GetPngs($category)
    {
        $directories = glob("assets/preview/$category/*.png");
        $directory = array();
        foreach($directories as $directories)
        {
            $directory[] = str_replace("assets/preview/$category/", "", $directories);   
        }
        return $directory;      
    }



回答3:


You are missing '.png' in your code just change

$directories = glob("assets/preview/$category/*");

to

$directories = glob("assets/preview/$category/*.png");


来源:https://stackoverflow.com/questions/27063706/php-search-directory-by-file-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!