special character renaming in php to underscores

霸气de小男生 提交于 2019-12-02 23:26:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!