Question

Ok. I've written a simple(ish) function to take an argument and return the same argument with the danger html characters replaced with their character entities.

The function can take as an argument either a string, an array or a 2D array - 3d arrays or more are not supported.

The function is as follows:

public function html_safe($input)
{   
    if(is_array($input)) //array was passed
    {
        $escaped_array = array();
        foreach($input as $in)
        {
            if(is_array($in)) //another array inside the initial array found
            {
                $inner_array = array();
                foreach($in as $i)
                {
                    $inner_array[] = htmlspecialchars($i);
                }
                $escaped_array[] = $inner_array;
            }
            else
                $escaped_array[] = htmlspecialchars($in);
        }
        return $escaped_array;
    }
    else // string
        return htmlspecialchars($input);
}

This function does work, but the problem is that I need to maintain the array keys of the original array.

The purpose of this function was to make it so we could literally pass a result set from a database query and get back all the values with the HTML characters made safe. Obviously therefore, the keys in the array will be the names of database fields and my function at the moment is replacing these with numeric values.

So yeah, I need to get back the same argument passed to the function with array keys still intact (if an array was passed).

Hope that makes sense, suggestions appreciated.

Was it helpful?

Solution

You can use recursion rather than nesting loads of foreaches:

function html_safe($input) {
    if (is_array($input)) {
        return array_map('html_safe', $input);
    } else {
        return htmlspecialchars($input);
    }
}

OTHER TIPS

Ok I think I've figured this one out myself...

my foreach loops didn't have any keys specified for example they were:

foreach($array_val as $val)

instead of:

foreach($array_val as $key => $val)

in which case I could have preserved array keys in the output arrrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top