Search code examples
phparraysopendirreaddir

Scandir Array display without file extensions


I'm using the following to create a list of my files in the 'html/' and link path.

When I view the array it shows, for example, my_file_name.php

How do I make it so the array only shows the filename and not the extension?

$path = array("./html/","./link/");
$path2=  array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/html/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/link/");
$start="";
$Fnm = "./html.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");

$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
       if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
            $folder2 = opendir($path[1]);
            $imagename ='';
            while( $file2 = readdir($folder2) ) {
                if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
                    $imagename = $file2;
                }
            }
            closedir($folder2);
        $result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n<a href=\"$file\">\n$file2\n</a><span class=\"glow\"><br></span>
</li>\n";
        fwrite($inF,$result);
       }
}
fwrite($inF,"");
closedir($folder);

fclose($inF);

Solution

  • pathinfo() is good, but I think in this case you can get away with strrpos(). I'm not sure what you're trying to do with $imagename, but I'll leave that to you. Here is what you can do with your code to compare just the base filenames:

    // ...
    $folder = opendir($path[0]);
    while( $file = readdir($folder) ) {
           if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
                $folder2 = opendir($path[1]);
                $imagename ='';
                $fileBaseName = substr($file,0,strrpos($file,'.'));
                while( $file2 = readdir($folder2) ) {
                    $file2BaseName = substr($file2,0,strrpos($file2,'.'));
                    if ($file2BaseName == $fileBaseName){
                        $imagename = $file2;
                    }
                }
                closedir($folder2);
            $result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n<a href=\"$file\">\n$file2\n</a><span class=\"glow\"><br></span>
    </li>\n";
            fwrite($inF,$result);
           }
    }
    

    I hope that helps!