PHP Regex for filename

2019-07-07 12:46发布

I made the user possible to change file names through a textarea, but now I'm having a regex problem.

As I see for Windows 7, these characters only are not allowed for filenames:

\ / : * ? < > |

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

I still really don't get the hang of it.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-07 13:15

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.

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

查看更多
倾城 Initia
3楼-- · 2019-07-07 13:29
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, e.g. 0-9

查看更多
登录 后发表回答