Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

People also ask

How do I remove an XML extension?

xml full extension, and you should simply rename the file (press F2 on a selected file, or choose "Rename" in the right mouse button menu), to get rid of the xml extension.

How do I remove a filename extension in Python?

To remove the extension from a filename using Python, the easiest way is with the os module path. basename() and path. splitext() functions. You can also use the pathlib module and Path and then access the attribute 'stem' to remove the extension from a filename.


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

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

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.


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.


Use PHP basename()

(PHP 4, PHP 5)

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

Outputs: string(4) "test"


This is a rather easy solution and will work no matter how long the extension or how many dots or other characters are in the string.

$filename = "abc.def.jpg";

$newFileName = substr($filename, 0 , (strrpos($filename, ".")));

//$newFileName will now be abc.def

Basically this just looks for the last occurrence of . and then uses substring to retrieve all the characters up to that point.

It's similar to one of your googled examples but simpler, faster and easier than regular expressions and the other examples. Well imo anyway. Hope it helps someone.


Recommend use: pathinfo with PATHINFO_FILENAME

$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);