简体   繁体   English

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

[英]I am trying to remove special characters but keep spaces and _ not working PHP

This is my code. 这是我的代码。 I am using regex to check when creating a folder it does not contain special characters but allow spaces and underscores in the name. 我正在使用正则表达式来检查创建文件夹时它不包含特殊字符但在名称中允许空格和下划线。 This code does not work but i cannot find the reason why. 此代码不起作用,但我找不到原因。 Please help me 请帮我

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

With preg_replace you replace the instances with something, from the php.net documentation : 使用preg_replace,你可以用php.net文档替换实例:

preg_replace() : Searches subject for matches to pattern and replaces them with replacement. preg_replace() :搜索主题匹配模式并用替换替换它们。

You want the preg_match function which returns a boolean on if there was a match. 你想要preg_match函数 ,如果有匹配则返回一个布尔值。

preg_match() : Searches subject for a match to the regular expression given in pattern. preg_match() :搜索主题以匹配模式中给出的正则表达式。

Your using preg_replace you should be using preg_match 你使用preg_replace你应该使用preg_match

preg_replace will return the string which will always be true, unless everything has been removed 除非删除了所有内容,否则preg_replace将返回始终为true的字符串

You can also use strpbrk() to search a string for any of a set of characters. 您还可以使用strpbrk()在字符串中搜索任何一组字符。

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

简单地使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM