[英]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);
Why not: 为什么不:
$filename = preg_replace('/[^.\w]/', '', $filename);
This will simply remove any character that is not a word character or period. 这将删除任何不是单词字符或句点的字符。
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. 正则表达式将匹配文件名中的任何非单词字符(此处的“单词字符”由类[a-zA-Z0-9_]
),只要存在扩展名即可。
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). 这也将考虑可能的文件名,例如file.name.txt
并正确返回filename.txt
(第一个点不是文件扩展名的点)。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.