[英]PHP Regex for filename
I made the user possible to change file names through a textarea, but now I'm having a regex problem. 我让用户可以通过textarea更改文件名,但现在我有一个正则表达式问题。
As I see for Windows 7, these characters only are not allowed for filenames: 正如我在Windows 7中看到的那样,这些字符仅允许用于文件名:
\\ / : * ? < > |
But I stubbornly, perhaps also wisely, choose to minimize the regex to ONLY these special characters: 但我固执地,或许也明智地选择将正则表达式最小化到这些特殊字符:
- _ .
All the others should have to be cut. 所有其他人都应该被削减。
Can someone help me out with this regex? 这个正则表达式有人可以帮助我吗?
preg_replace all but: A-Za-z0-9
and - _ .
preg_replace all:
A-Za-z0-9
和- _ .
I still really don't get the hang of it. 我仍然真的没有掌握它。
preg_replace('/[^A-Za-z0-9 _ .-]/', '', $filename);
The [] is a character class and the ^ negates it. []是一个字符类,^否定它。 So it literally matches anything other than the chars in that group.
因此,除了该组中的字符之外,它实际上匹配任何其他内容。
Note that -
is at the end, as it is a special range character if used elsewhere, eg 0-9 请注意
-
最后,因为如果在别处使用它是一个特殊的范围字符,例如0-9
Your question has the character-set pretty-much laid out already. 你的问题已经完成了很多字符集。 You'll just need to plug it into
preg_replace()
to get it going. 你只需要将它插入
preg_replace()
即可。
Try this: 尝试这个:
$filename = preg_replace('/[^a-zA-Z0-9_.-]/', '', $filename);
The ^
at the beginning of the character set, surrounded by []
, states to not -match the list of characters. 由
[]
包围的字符集开头的^
表示不匹配字符列表。 Therefore, the line can be read as "replace the characters that are not the following". 因此,该行可以被读作“替换不是以下的字符”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.