Delete all decimal numbers, but for the last time

I would like to know a way to remove all decimals from a file name, but the last one. I need to keep the latter, because the extension follows this.

Example:

abc.def.ghij-klmnop.q234.mp3

This file should look like

abcdefghij-klmnopq234.mp3

Some extensions are longer than 3 char.

+3
source share
4 answers

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

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

After doing the above, $nodotswill contain abcdefghij-klmnopq234.mp3. A regular expression basically indicates the coincidence of all periods followed by another period. Therefore, the last period will not match. We replace all matches with an empty string, and we leave the desired result.

+11
source

:

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

, , pathinfo str_replace.

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

, $s - .

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

All Articles