使用 preg_replace 删除不需要的字符但需要保留 '.'

Using preg_replace to remove unwanted characters but need to keep '.'

我正在使用 php preg_replace 来清理我的上传文件,我想删除任何不需要的字符,例如 (&?/\~{}[ ] - 也就是删除空格)等,但我不想删除“。” (完整 stop/period)因为它删除了文件扩展名。

我一直在网上搜索,但一直在寻找删除所有特殊字符或过于复杂的正则表达式。

这是我当前的代码,但如您所见,它正在删除“.”

$filename = preg_replace("/[^a-zA-Z0-9]/", '', "{$uploadedFile}");

肯定有一个我错过的答案,因为这似乎是一个相当直接的请求,有人知道我需要包括什么吗?

一个字符class列出你要allow/disallow的字符。所以在你的角色 class 中添加 . 然后你就可以开始了。

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

演示:https://regex101.com/r/bE5qI4/1

更多信息:http://www.regular-expressions.info/charclass.html

另外值得注意的是:

In most regex flavors, the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (), the caret (^), and the hyphen (-).