foreach循环不起作用

3D-*_*tiv 1 php

我正在尝试使用foreach循环来搜索$ _POST中的单词,但它不起作用?帮助是预先确定的.

$unsafeWords = array('content-typ','bcc','cc');
foreach ($_POST as $key => $input) {
    foreach ($unsafeWords as $value) {
        $_POST = str_ireplace($value, "", $input) ;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ker 5

不要用字符串覆盖$ _POST数组

$unsafeWords = array('content-typ','bcc','cc');
foreach ($_POST as $key => $input) {
    foreach ($unsafeWords as $value) {
        $_POST[$key] = str_ireplace($value, "", $input) ;
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我不喜欢覆盖原始的$ _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) ;
}
Run Code Online (Sandbox Code Playgroud)

并且你没有用空格替换,你用空字符串替换(有效地从你的$ _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)) ;
}
Run Code Online (Sandbox Code Playgroud)