在 php 中将特殊字符重命名为下划线 [英] special character renaming in php to underscores
问题描述
重命名表单中收集的所有特殊字符以替换为下划线的好方法是什么?
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
我正在绑定一个由用户下载的软件,在该软件中,重命名约定是用下划线替换上面列出的任何字符.为了让我的基于 Web 的应用程序正常工作,它需要在表单字段中收集一些信息,该字段的名称与用户在软件中输入的名称完全相同,并且命名约定正确.因此,当 mp3 文件上传时,ajax 调用检查文件时,它将完全匹配,从而导致其余功能失效.
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.
推荐答案
你已经差不多了:
$str = "Zebo's [Test]";
echo preg_replace("~['.!,;:@#$%^&*|()?/\\<> \t\r\n\[\]]~", "_", $str);
输出: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:
`îõ§¶þäô
这篇关于在 php 中将特殊字符重命名为下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!