替换某些字符同时允许 unicode (PHP)
因此,我在我们正在开发的网站上有一个搜索框,它将在数据库中搜索英语和希腊语产品字符串。我试图清除各种特殊字符的文本输入,例如: / 。 , ' ] [ % & _ 等,并用空格替换它们或完全删除它们。即使它们的两个实例也应该被删除,比如 ^^、&&、[[ 等。
我一直在摆弄 preg_replace 但找不到解决方案...
提前致谢。
So I got a search box in a site we're developing that will search in a database with both English and Greek product strings. I'm trying to clear the text input from all kinds of special characters like: / . , ' ] [ % & _ etc. and replace them with a space or totally delete them. Even double instances of them should be deleted, like ^^, &&, [[ etc.
I have been messing around with preg_replace but can't find a solution...
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我终于想出了这个:
它似乎适合我的需要。它允许使用希腊字符(甚至带有重音符号)、字母数字和空格。用空格替换其他所有内容。感谢大家的快速回复。
I finally came up with this:
It seems to work for what I need. It allows Greek characters (even with accents), alphanumerical and spaces. Replaces everything else with a space. Thanks for the fast response guys.
使用 preg_replace 你可以做你想要的事情。在下一个示例中,所有非 az 也不是 AZ,也不是 /_ | + - 字符被替换为 '' (什么都没有,空字符串)
添加您想要允许在该列表中的字符,您将拥有您的函数。
另一种方法是使用 str_replace() ,但在这里您必须在不同的函数调用中一一插入要删除的所有元素。
我希望它有帮助
With preg_replace you can do what you are looking for. In the next example all non a-z nor A-Z, nor / _ | + - characters are replaced by '' (nothing, empty string)
add the characters you want to allow in that list and you will have your function.
Other way would be with
str_replace()
but here you have to insert one by one all the elements that you want to remove in different function calls.I hope it helps
为什么不创建一个数组并使用 str_replace 呢?
将数组中的所有值替换为“”,即什么也不替换。
Why not make an array and use str_replace?
Replaces all values of the array with "", in otherwords nothing.