dongyou2305 2011-08-02 06:39
浏览 57
已采纳

在PHP中扩展了addslashes功能

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!

  • 写回答

2条回答 默认 最新

  • ds2128629 2011-08-02 07:03
    关注

    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
                    )
    
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误