How can I iterate a multidimensional array and filter on string nodes? I'm trying to create an easy way to sanitize data coming into my application via POST and think this would be really handy.
3
-
possible duplicate of Exclude Items in IteratorGordon– Gordon2011-11-16 08:06:44 +00:00Commented Nov 16, 2011 at 8:06
-
possible duplicate of Foreach with arrays within arraysGordon– Gordon2011-11-16 08:07:50 +00:00Commented Nov 16, 2011 at 8:07
-
alternative php.net/manual/en/function.filter-input-array.php with FILTER_CALLBACKGordon– Gordon2011-11-16 08:09:58 +00:00Commented Nov 16, 2011 at 8:09
Add a comment
|
2 Answers
You can use a recursive function to traverse the array and filter its string components. For example:
function doFilter($arr) {
foreach ($arr as $key => $value) {
if (is_string($value)) {
$arr[$Key] = sanitize($value);
} else if (is_array($value)) {
$arr[$key] = doFilter($value);
}
}
return $arr;
}
function sanitize($str) {
// Perform necessary steps to sanitize $str
return $str;
}
Comments
You need to use Recursion
function sanitizePost($post) {
if (is_array($post)){
foreach ($post as $k => $p) {
$post[$k] = sanitizePost($p);
}
} else {
$post = sanatizeStringFunction($post); // may be use regex or something
}
return $post;
}