php 如何替换php中除下划线和句点外的所有特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21276423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to replace all special characters except underscore and period in php?
提问by maniteja
Can any one please show me how i can replace all special characters in a string except the underscore and the period symbols.And also I've been trying to understand how to make this replace patterns reading the PHPmanual and its so confusing for a beginner like me so is there any other documentation or tutorial that is made easy for beginners so that i don't have to post another question like this and trouble you people every time i want to use this function?
任何人都可以告诉我如何替换字符串中除下划线和句点符号之外的所有特殊字符。而且我一直试图了解如何在阅读PHP手册时使用这种替换模式,这对初学者来说如此令人困惑所以有没有其他文档或教程对初学者来说很容易,这样我就不必在每次我想使用这个功能时发布另一个这样的问题并给你们带来麻烦?
preg_replace('/[^a-zA-Z0-9]/', '', $string);
this is what i have it replaces all the special characters but i want to except _and ..
这就是我所拥有的,它替换了所有特殊字符,但我想除了_和 .。
回答by falsetru
Put _and .to the negated set of characters ([^...]):
将_和放在.否定的字符集 ( [^...]) 上:
$string = preg_replace('/[^a-zA-Z0-9_.]/', '', $string);
You should not omit $string = ..because preg_replacereturn replaced string. It does not change the string in place.
你不应该省略,$string = ..因为preg_replace返回替换的字符串。它不会就地更改字符串。
回答by jiang
You can use some php filter widget like Purifier (to set a whitelist for input)...
您可以使用一些 php 过滤器小部件,如 Purifier(为输入设置白名单)...
But Still, we would like to suggest you to learn regex!
但是,我们还是建议您学习正则表达式!

