简体   繁体   English

删除最后一个字符之后和最后一个点之前的所有空格

[英]Remove all spaces after last character and before final dot

I have some rar files which im using a PHP to extract the contents, However some of the files have a space just before the extension and i can't figure out how to remove it. 我有一些rar文件,它们使用PHP提取内容,但是其中一些文件在扩展名前有一个空格,我不知道如何删除它。

Example: 例:

This is a file.name (Testing) .rar

I want to remove the space just after the ) and .rar but i don't want the remove any other like the one in file.name 我想删除)和.rar之后的空格,但我不希望删除其他任何文件,例如file.name中的空格。

Is this possible ? 这可能吗 ?

You can use the following regex to match: 您可以使用以下正则表达式进行匹配:

\s*(?=(?:\.[^.]+)?$)

And replace with '' (empty string) 并替换为'' (空字符串)

See DEMO 演示

Without regex: 没有正则表达式:

$filename="This is a file.name (Testing) .rar";
if ($dot=strrpos($filename,".")) {
    $filename=trim(substr($filename,0,$dot)).substr($filename,$dot);
}

The following code uses a PCRE to replace the whitespace between the last non-whitespace character before the final dot and the final dot: 以下代码使用PCRE替换最后一个点之前的最后一个非空白字符和最后一个点之间的空白:

$filename = "This is a file.name (Testing) .rar";
echo preg_replace("/^(.*?)\s*(\.[^\s\.]+)$/", "\\1\\2", $filename);

// will output:   This is a file.name (Testing).rar

Limitation: the filename extension itself must not contain any whitespace. 限制:文件扩展名本身不能包含任何空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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