Search code examples
phpfilenamesexplodeperiodscandir

exploding a file name to separate the name and extension won't work in PHP?


I'm building a class that returns an string that will include files in a folder automatically, kinda like a loader for an HTML file.

Here's the method that will be called:

function build_external_file_include($_dir){
    $_files = scandir($_dir);
    $_stack_of_file_includes = "";//will store the includes for the specified file.
foreach ($_files as $ext){
    //split the file name into two;
    $fileName = explode('.',$ext, 1);//this is where the issue is.

    switch ($fileName[1]){
        case "js":
            //if file is javascript
             $_stack_of_file_includes =  $_stack_of_file_includes."<script type='text/javascript' src='".$dir.'/'.   $ext ."'></script>";

            break;
        case "css";//if file is css
             $_stack_of_file_includes =  $_stack_of_file_includes."<link rel=\"stylesheet\" type=\"text/css\" href=\"".$dir.'/'. $ext."\" />";
            break;
        default://if file type is unkown
             $_stack_of_file_includes =  $_stack_of_file_includes."<!-- File: ".  $ext." was not included-->";
    }


}
return $_stack_of_file_includes;
}

So, this runs without any errors. But, it doesn't do what it's supposed to do... or at least what I intend it to do. Technically speaking here,

$fileName[1] should be the extension js

$fileName[0] should be name of the file main

but

$fileName[0] is main.js.

does explode not recognize .?

Thank you in advance.


Solution

  • You're forcing your resulting array to have 1 element, which causes it to have the entire filename.

    explode( '.', $ext, 1 )
    

    should instead be

    explode( '.', $ext );
    

    Proof: http://codepad.org/01DLpo6H