简体   繁体   中英

Remove all dots in filename except the dot before the file extension

I am trying to sanitize a filename.

I would like to know of a way to remove all decimals from a files name except the last one. I need to keep the last one because the extension follows that.

EXAMPLE:

abc.def.ghij-klmnop.q234.mp3

This file should look like

abcdefghij-klmnopq234.mp3

Some extensions are longer than 3 characters.

You can use a regex with a positive lookahead. Like this:

$withdots = 'abc.def.ghij-klmnop.q234.mp3';
$nodots = preg_replace('/\.(?=.*\.)/', '', $withdots);

After executing the above, $nodots will contain abcdefghij-klmnopq234.mp3 . The regular expression is basically saying match all periods that are followed by another period. So the last period won't match. We replace all matches with an empty string, and we're left with the desired result.

That should do it:

$file = 'abc.def.ghij-klmnop.q234.mp3';
$parts = pathinfo($file);
$filename = str_replace('.', '', $parts['filename']).'.'.$parts['extension'];

You could also do this, it should be faster then using pathinfo & str_replace.

$parts  = explode('.', 'abc.def.ghij-klmnop.q234.mp3');
$ext    = array_pop($parts);
$nodots = implode('', $parts) . '.' . $ext;

Assuming $s is the name of the file.

$s = (($i = strrpos($s, '.')) === false) ? $s :
    str_replace('.','',substr($s,0,$i)).substr($s,$i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM