How to remove the file extension: Stripping the String, PHP substr() function

96

Striping the file extension is valuable on many levels.

<?php

$filename = foobar.exe
function returnFileName($fileName) {

return key(explode(“.”, $fileName));

}
// returns foobar

function returnFileExtension($fileName) {

return end(explode(“.”, $fileName));

}

// returns exe

?>

Result: foobar

Note: Spaces count, so count them!



6 comments ↓

If you found this post useful click the share this button. Contribute below by adding a comment, no registration is required.

  • Rider says on 02.29.08 at 3:04 pm comment #1

    What if the file extension is only 2 character long?

  • anonymous says on 02.29.08 at 7:10 pm comment #2

    just use $my_file= substr($my_file, 0 , -3);

  • theproblem says on 04.28.09 at 10:45 am comment #3

    if you don’t know how long the extension is, you will need to explode the string at the ‘.’, then add them back together except for the final part of the array (sizeof -1)

  • kadimi says on 08.01.09 at 2:21 pm comment #4

    Funny… lol,

    You can remove the file extension even if it’s 100 characters long with this,

    $no_extension = implode(‘.’, explode(‘.’, $filename, -1));

    Of course there is better, just think about it…

  • headalien says on 10.18.10 at 5:39 pm comment #5

    Or you can use pathinfo( ) which is part of php since ver 4

    $path_parts = pathinfo(‘/www/htdocs/inc/lib.inc.php’);

    echo $path_parts['dirname'], “\n”;
    echo $path_parts['basename'], “\n”;
    echo $path_parts['extension'], “\n”;
    echo $path_parts['filename'], “\n”; // since PHP 5.2.0

    The above example will output:

    /www/htdocs/inc
    lib.inc.php
    php
    lib.inc

    for more info see: http://php.net/manual/en/function.pathinfo.php

  • Web Hosting says on 10.05.11 at 10:35 am comment #6

    Unfortunately PHP’s pathinfo() doesn’t remove all the extensions if a filename has many extensions such as file.inc.php, for that purpose use the following:

    $fileArray = explode(“.”, $filename);
    return($fileArray[0]);

Leave a Comment