php 正则表达式匹配除字母和数字以外的所有字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2167145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to match all characters except letters and numbers
提问by Timay
I want to clean the filenames of all uploaded files. I want to remove all characters except periods, letters and numbers. I'm not good with regex so I thought I would ask here. Can someone point me to a helpful site or show me how to put this together? I'm using PHP.
我想清理所有上传文件的文件名。我想删除除句点、字母和数字以外的所有字符。我不擅长正则表达式,所以我想我会在这里问。有人可以将我指向一个有用的站点或告诉我如何将它们组合在一起吗?我正在使用 PHP。
回答by YOU
$newfilename=preg_replace('/[^a-zA-Z0-9.]/','',$filename);
回答by kennytm
s/[^.a-zA-Z\d]//g
(This is a Perl expression of how to use the RegExp. In PHP you do:
(这是一个关于如何使用 RegExp 的 Perl 表达式。在 PHP 中,您可以:
$output = preg_replace('/[^.a-zA-Z\d]/', '', $input);
回答by Marcio Mazzucato
Try to use this:
尝试使用这个:
$cleanString = preg_replace('#\W#', '', $string);
It will remove all but letters and numbers.
它将删除除字母和数字之外的所有内容。

