Exoon
Exoon

Reputation: 1553

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.

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

Is this possible ?

Upvotes: 0

Views: 504

Answers (3)

stj
stj

Reputation: 9097

The following code uses a PCRE to replace the whitespace between the last non-whitespace character before the final dot and the final dot:

$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.

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

You can use the following regex to match:

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

And replace with '' (empty string)

See DEMO

Upvotes: 1

umka
umka

Reputation: 1655

Without regex:

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

Upvotes: 0

Related Questions