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

96

Striping the file extension is valuable on many levels. If i could have a nickel for every time I need to strip the file extension I'd have close to 3 bucks. One method to achieve stripped extensions is the PHP substr(), which takes in the String, Starting point, Ending point. To start from the end of the string use negative values. i.e. substr("my chicken", 0, -2) would make it "my chick", perfect

<?php

$my_file = "foobar.jpg";
$my_file= substr($my_file, 0 , -4);
echo $my_file;

?>

Result: foobar

Note: Spaces count, so count them!



4 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…

Leave a Comment