我正在尝试使用foreach循环在$_POST中搜索单词,但它不起作用?帮助是精准的。
$unsafeWords = array('content-typ','bcc','cc');
foreach ($_POST as $key => $input) {
foreach ($unsafeWords as $value) {
$_POST = str_ireplace($value, "", $input) ;
}
}
发布于 2011-03-21 22:27:41
不要用字符串覆盖$_POST数组
$unsafeWords = array('content-typ','bcc','cc');
foreach ($_POST as $key => $input) {
foreach ($unsafeWords as $value) {
$_POST[$key] = str_ireplace($value, "", $input) ;
}
}
虽然我不喜欢覆盖原始的$_POST数组,但我更喜欢构建一个新的清理值数组
请注意,您不需要循环$unsafeWords数组,但可以将其作为数组直接传递给str_ireplace()
编辑
示例使用$unsafeWords数组作为str_ireplace()的参数,而不是使用foreach()遍历该数组并为每个条目调用str_ireplace()。
$unsafeWords = array('content-type','bcc','cc');
foreach ($_POST as $key => $input) {
$_POST[$key] = str_ireplace($unsafeWords, "", $input) ;
}
而且不是用空格替换,而是用空字符串替换(有效地从$_POST变量中删除不安全的字符串)
编辑2个
我想把这个放到foreach循环中也可以吧?
不完全是..。如果您只是将其作为额外的一行添加到循环中,那么您将覆盖之前的替换。按如下方式操作:
$unsafeWords = array('content-type','bcc','cc');
foreach ($_POST as $key => $input) {
$_POST[$key] = str_ireplace($unsafeWords, "", filter_var($input, FILTER_SANITIZE_STRIPPED)) ;
}
发布于 2011-03-21 22:27:30
您正试图用字符串值覆盖$_POST
(数组)。正确的方法是:
foreach ($_POST as &$input) {
$input = str_ireplace($unsafeWords, array(), $input) ;
}
上面的代码还利用了其他几个特性(使用引用作为循环变量的foreach
,str_ireplace
接受数组)来缩短代码。
发布于 2011-03-21 22:28:37
不完全清楚你在问什么,但这是:
$_POST = str_ireplace($value, "", $input) ;
肯定不会像你期望的那样。您可能需要:
$_POST[$key] = str_ireplace($value, "", $input) ;
https://stackoverflow.com/questions/5378975
复制相似问题