Search code examples
phppreg-replaceexplode

PHP how to remove the last part of a filename after underscore


A filename looks like whatever_test_123234545.gif.

What is the easiest way to remove the last underscore followed by all characters and numbers after it but not the the dot extension.

In other words i want whatever_test_123234545.gif to look like whatever_test.gif. A filename can have a random number of underscores. I just want to remove the last part before .ext.


Solution

  • This will remove everything between the last underscore and the .. If the filename does't have a . or doesn't have an _ it will not change the filename:

    $filename = 'whatever_test_123234545.gif';
    $new_filename = preg_replace('/_[^_.]*\./', '.', $filename);
    

    And to actually rename the file:

    rename($filename, $new_filename);