问题
What's a good way to rename all special characters collected in a form to be replaced with an underscore?
Here's an example of the special characters to be replaced:
[.!,;:@#$%^&*|()?/\\\<>] space tab CR NL
I am tying into a piece of software that is downloaded by a user, and in that software, the renaming convention is to replace any of the characters listed above with an underscore. And for my web based application to work properly, it needs to collect some information in a form field that is named exactly as the user put it in the software, and have the naming convention work right. So when the mp3 file gets uploaded, and the ajax call checks for a file, it will match exactly, thus tripping off the rest of the functionality.
回答1:
You're almost there already:
$str = "Zebo's [Test]";
echo preg_replace("~['.!,;:@#$%^&*|()?/\\<> \t\r\n\[\]]~", "_", $str);
Output: Zebo_s__Test_
Edited to include [
, ]
, and '
properly - didn't realize you meant that you wanted to replace those.
By the way... You say you want to replace "all special characters," and that your list above is just an "example." You may want to do something broader, like this:
preg_replace("~[^A-Za-z0-9]~", "_", $str);
This would also catch characters like the backtick and other special characters, such as:
`îõ§¶þäô
回答2:
You can use:
$repl = preg_replace('~[.!,;:@#$%^&*|()?/\\\<>]~', '_', $str);
来源:https://stackoverflow.com/questions/21353169/special-character-renaming-in-php-to-underscores