How to remove extension from string (only real extension!)

Use PHP basename()

(PHP 4, PHP 5)

var_dump(basename('test.php', '.php'));

Outputs: string(4) "test"


http://php.net/manual/en/function.pathinfo.php

pathinfo — Returns information about a file path

$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'

From the manual, pathinfo:

<?php
    $path_parts = pathinfo('/www/htdocs/index.html');

    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
?>

It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg as /path/to/my/file.jpg.


Try this one:

$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);

So, this matches a dot followed by three or four characters which are not a dot or a space. The "3 or 4" rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.

Tags:

Php