我试图删除特殊字符,但保留空格和_不工作PHP

时间:2013-12-16 11:54:03

标签: php

这是我的代码。我正在使用正则表达式来检查创建文件夹时它不包含特殊字符但在名称中允许空格和下划线。此代码不起作用,但我找不到原因。请帮帮我

if (preg_replace("/[^\w ]+/", "", $filename))
{
  echo 'A file name can not contain The Following Characters: \ / : * ? " < > | %';
}else{
  // do something
}

4 个答案:

答案 0 :(得分:4)

使用preg_replace,您可以使用php.net documentation

替换实例
  

preg_replace():搜索主题匹配模式并将其替换为替换。

如果匹配,你想要preg_match function返回一个布尔值。

  

preg_match():搜索主题以匹配模式中给出的正则表达式。

答案 1 :(得分:2)

您使用preg_replace时应该使用preg_match

preg_replace将返回始终为true的字符串,除非所有内容都已删除

答案 2 :(得分:1)

您还可以使用strpbrk()在字符串中搜索任何一组字符。

if (strpbrk($directoryName, "\\/?%*:|\"<> ") === FALSE) {
    /* $directoryName is legal; doesn't contain illegal character. */
}
else {
    /* $directoryName contains at least one illegal character. */
}

答案 3 :(得分:0)

只需使用

preg_replace('/[^a-zA-Z0-9%\[\]\.\(\)%&-]/s', '', $Your_String);