删除所有非单词字符,但“。”

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);

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

Why not:

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

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

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);