简体   繁体   English

删除文件名中的所有点,除了文件扩展名之前的点

[英]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.

相关问题 PHP-如何在点扩展名前的括号内增加文件名ID? - PHP - How to increment a filename id within braces before the dot extension? 带有条件的正则表达式在文件扩展名之前用点替换“-”或“_” - regex with condition to replace "-" or "_" before the file extension with a dot 删除除点以外的所有符号,并删除括号内的所有内容 - Remove all symbols except Dot and also remove everything inside braces PHP:如何在文件上传时删除文件名中不必要的点? - PHP: How to remove unnecessary dots in filename on file upload? .htaccess重写,尝试除去索引文件以外的所有文件上的.html文件扩展名 - .htaccess rewrite, trying to remove .html file extension on all files EXCEPT index file 从文件名中删除扩展名,但保持扩展名与文件关联 - remove extension from filename, but keep extension associated to file 删除最后一个字符之后和最后一个点之前的所有空格 - Remove all spaces after last character and before final dot 使用PHP获取给定URL的文件名并删除文件扩展名 - get the filename of a given URL using PHP and remove the file extension PHP删除之前的所有字符,除了最后一个数字 - PHP remove all characters before, except last number 在Handler文件上传之前从文件名中删除撇号 - Remove apostrophes from filename before the Handler file upload it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM