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!

3 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);

  • turox says on 08.06.08 at 1:14 am comment #3

    what if i want to cut a string until i find a point.

    i.e.

    In ultricies. Integer diam nibh, hendrerit ac, tempus nec, cursus non, eros. In aliquam, leo non laoreet sodales, sem tortor vulputate enim, non pharetra odio enim molestie erat. Proin ac urna. Curabitur pharetra urna ultricies metus iaculis vulputate. Sed adipiscing, dolor vel sagittis scelerisque, arcu ligula imperdiet ligula, eu fermentum est urna vel lorem. Donec eros urna, consequat vel, ultrices quis, congue quis, nulla. [see more]

    if a click [see more] i can see the complete text

Leave a Comment