[英]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.某些扩展名超过 3 个字符。
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
.执行上述操作后,
$nodots
将包含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.你也可以这样做,它应该比使用 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
是文件名。
$s = (($i = strrpos($s, '.')) === false) ? $s :
str_replace('.','',substr($s,0,$i)).substr($s,$i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.