开发者

Extended addslashes function in PHP

Hi can somebody help me with building an extended addslashes function, which will work with mixed combination of objects and arrays. For example i have this Object:

  $object = new stdClass;
  $object2 = new stdClass;
  $object2->one = "st'r2";
  $object3 = new stdClass;
  $object3->one = "st'r3";
  $object->one = "s'tr";
  $object->two = array($object2);
  $object->obj = $object3;

And i would like to get this object back escaped and with the same structure. I have started some experiments and i get something like this:

function addslashes_extended($arr_r){
            if(is_array($arr_r)){
                foreach ($arr_r as $key => $val){
                    is_array($val) ? addslashes_extended($val):$arr_r[$key]=addslashes($val);
                }
            unset($val);
            }else if(is_object($arr_r)){
                $objectProperties = get_object_vars($arr_r);
                foreach($objectProperties as开发者_开发百科 $key => $value){
                    is_object($value) ? addslashes_extended($value):$arr_r->{$key}=addslashes($value);
                }
            }
        return $arr_r;
}

But this is not going to work, i have to work with passing by reference i think, but i have no clue how, other solutions would be nice to have too, thanks in advance!


Try this (using array_walk):

error_reporting(E_ALL ^ E_STRICT);
ini_set('display_errors', 'on');

$data = array(
    "fo'o",
    'bar' => "foo'bar",
    'foobar' => array(
        1, 2, 'someObj' => json_decode('{"prop1": "a", "prop2": "b\'c"}')
    )
);

class Util
{
    public static function addslashes_extended(&$mixed) {
        if (is_array($mixed) || is_object($mixed)) {
            array_walk($mixed, 'Util::addslashes_extended');
        }
        elseif (is_string($mixed)) {
            $mixed = addslashes($mixed);
        }
    }

}

Util::addslashes_extended($data);

print_r($data);

Output ( http://codepad.org/nUUYKWrn ):

Array
(
    [0] => fo\'o
    [bar] => foo\'bar
    [foobar] => Array
        (
            [0] => 1
            [1] => 2
            [someObj] => stdClass Object
                (
                    [prop1] => a
                    [prop2] => b\'c
                )

        )

)


To pass by reference, you use & before the variable name, quick example:

function inc(&$var) {
    $var++;
}

$x = 5;
inc($x);
echo $x; //Prints: 6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜