Scandir:检查具有相同名称的文件(不包括扩展名)

时间:2013-02-28 22:46:29

标签: php scandir

是否可以检查具有相同文件名的文件(仅在文件扩展名方面有所不同)并且只显示一次名称?

if (is_dir($dir_path)) {

    $files = scandir($dir_path);

    foreach($files as $file) {

        if ( !in_array( $file, $exclude_all ) ) {

            $path_to_file = $dir_path . $file;
            $bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
            $extension = pathinfo( $path_to_file, PATHINFO_EXTENSION );

            echo 'Path to file: ' . $path_to_file . '<br />';
            echo 'Bare file name: ' . $bare_name . '<br />';
            echo 'Extension: ' . $extension . '<br />';         

        }
    }
}

2 个答案:

答案 0 :(得分:0)

you can try this:

//first save all files in an array
$bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
if(!in_array($bare_name, $files)){
 $files[] = $bare_name;
}

现在$ files包含唯一文件名

答案 1 :(得分:0)

试试这个

if (is_dir($dir_path)) {

$tmpBareNames = array();

$files = scandir($dir_path);

foreach($files as $file) {

    if ( !in_array( $file, $exclude_all ) ) {

        $path_to_file = $dir_path . $file;
        $bare_name = pathinfo( $path_to_file, PATHINFO_FILENAME );
        if(!in_array($bare_name,$tmpBareNames))
            $tmpBareName[] = $bare_name;
        else break;
        $extension = pathinfo( $path_to_file, PATHINFO_EXTENSION );

        echo 'Path to file: ' . $path_to_file . '<br />';
        echo 'Bare file name: ' . $bare_name . '<br />';
        echo 'Extension: ' . $extension . '<br />';         

    }
}
}