php 从字符串中删除空格和特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10971233/
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
remove whitespace and special character from string
提问by raju
i am using this code to save the uploaded file but the problem is it is allowing the file with name with special character and space. for example it is allowing
我正在使用此代码来保存上传的文件,但问题是它允许名称带有特殊字符和空格的文件。例如它允许
hi how are you
but i dont want to allow any space ,special charater etc. here is my code .i tried with preg_replace in uri but after that i tried to upload file but nothing got uploaded.
但我不想允许任何空间,特殊字符等。这是我的代码。我尝试在 uri 中使用 preg_replace 但之后我尝试上传文件但没有上传。
function save_file($file) {
$allowed_ext = array('jpg','png','gif','jpeg');
$ext = $file['name'];
$ext = strtolower($ext);
if (in_array($ext, $allowed_ext)) {
die('Sorry, the file type is incorrect:'.$file['name']);
}
$fname = date("H_i",time()).'_'.get_rand(5);
$dir = date("Ym",time());
$folder = 'uploads/userfiles/'.$dir;
$uri = $folder.'/'.$fname.'.'.$ext;
if (!is_dir($folder))
mkdir($folder, 0777);
if (copy($file['tmp_name'],$uri))
return $uri;
else {
return false;
}
}
回答by John
To strip non letters out of a string you can use the following regular expression
要从字符串中去除非字母,您可以使用以下正则表达式
$input = preg_replace("/[^a-zA-Z]+/", "", $input);

