Felix Bernhard
Felix Bernhard

Reputation: 415

Remove all non-word characters but "."

What is the easiest way to remove all non-word characters of a filename?

The dot at the end before the extension is obviously needed, so all symbols like "-" or "*" or "?" should be removed except "."

Something like this:

$filename = preg_replace("/[^\.]\W/", "", $filename);

Upvotes: 2

Views: 2667

Answers (3)

Jerry
Jerry

Reputation: 71578

I would use something like that:

$filename = preg_replace("/\W(?=.*\.[^.]*$)/", "", $filename);

The regex will match any non-word character ('word character' here is defined by the class [a-zA-Z0-9_]) from a filename as long as there's a period for the extension.

This will also take into consideration possible file names such as file.name.txt and correctly return filename.txt (the first dot not being the dot for file extension).

Upvotes: 4

Sabuj Hassan
Sabuj Hassan

Reputation: 39395

My preference is

$filename = preg_replace('/[^.a-zA-Z]/', '', $filename);

If you want to add the digits too, then

$filename = preg_replace('/[^.a-zA-Z0-9]/', '', $filename);

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149040

Why not:

$filename = preg_replace('/[^.\w]/', '', $filename);

This will simply remove any character that is not a word character or period.

Upvotes: 3

Related Questions