发誓过滤器区分大小写
我的函数有一个小问题:
function swear_filter($string){
$search = array(
'bad-word',
);
$replace = array(
'****',
);
return preg_replace($search , $replace, $string);
}
它应该将“bad-word”转换为“**”,但问题是大小写敏感,
例如。如果用户输入“baD-word”,它就不起作用。
I have a little problem with my function:
function swear_filter($string){
$search = array(
'bad-word',
);
$replace = array(
'****',
);
return preg_replace($search , $replace, $string);
}
It should transform "bad-word" to "**" but the problem is the case sensivity
eg. if the user type "baD-word" it doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$search
数组中的值不是正则表达式。首先,解决这个问题:
然后,您可以应用
i
标志来不区分大小写:您不需要
g
标志来匹配全局 (即每次不止一次)因为preg_replace
将为您处理该问题。但是,您可能可以使用 单词边界元字符
\b
以避免将“坏词”字符串匹配到另一个单词内。这可能会对您如何形成“坏词”列表产生影响。现场演示。
如果您不想让这些实现细节污染
$search
,那么你可以用更多的编程方式做同样的事情:(我没有使用最近的 PHP lambda 语法,因为键盘不支持它;如果你感兴趣的话可以查一下!)
现场演示。
更新 完整代码:
The values in your
$search
array are not regular expressions.First, fix that:
Then, you can apply the
i
flag for case-insensitivity:You don't need the
g
flag to match globally (i.e. more than once each) becausepreg_replace
will handle that for you.However, you could probably do with using the word boundary metacharacter
\b
to avoid matching your "bad-word" string inside another word. This may have consequences on how you form your list of "bad words".Live demo.
If you don't want to pollute
$search
with these implementation details, then you can do the same thing a bit more programmatically:(I've not used the recent PHP lambda syntax because codepad doesn't support it; look it up if you are interested!)
Live demo.
Update Full code:
我想你的意思是
I think you mean
您甚至需要使用正则表达式吗?
做出以下假设。
1) $string 包含当前本地可接受的字符
2) $search 数组的所有内容都是小写
编辑: 3) 整个字符串包含坏词
我想这只有在字符串被拆分并基于每个单词进行评估时才有效。
Do you even need to use regex?
makes the following assumptions.
1) $string contains characters acceptable in the current local
2) all contents of the $search array are lowercase
edit: 3) Entire string consists of bad word
I suppose this would only work if the string was split and evaluated on a per word basis.