PHP array Encoding and Decoding:Need a function for encoding and decoding string or array with delimiters or array itself

余生颓废 提交于 2019-11-29 18:36:44

I wrote you a prototype for an extended class from this base class. Not sure what $PatternFlip is for, its not accessible in this class so you'll have to change it as you see necessary. If you want the result in a different format you can add functions to the class.

class MyProtector extends Protector {

var $Object;
var $encode;//1 means encode, not 1 means decode
var $result;

function __MyProtector($obj="",$encode=0,$pattern="") {
   $this->$Object=$obj;
   if($encode){//encode object
       $this->$EncodePattern=$pattern;
       $this->$result=smartEncode($obj);
   }else{//decode object
       $this->$DecodePattern=$pattern;
       $this->result=smartDecode($obj);
}
}

private function smartEncode($object){
   //encodes string or array
   if(is_array($object){
       return encodeArray($object);
   }else if(is_string($object)){
       return encodeString($object);
   }

   return 0;

}

private function smartDecode($object){
   //encodes string or array
   if(is_string($object)&&strpos("&",$object)===1){
       return encodeDelimiter($object);
   }else if(is_string($object)){
       return encodeString($object);
   }

   return 0;

}
private function decodeDelimiter($object){
   $a=explode("&",$string);//will only work if your encoding does not include "&"!
   $aDecoded=array();
   $k=0; 
   foreach($a as $i){
     $this->toDecode=$i;
     $aDecoded[$k]=$this->Decode();
     $k++;          
   }
   return $aDecoded;


}

private function decodeString($s){
$this->toDecode=$s;
    return $this->Decode();
}

private function encodeString($s){
   $this->toEncode=$s;
   return $this->Encode();
}

private function encodeArray($s){
   foreach($s as $i){
  $this->toEncode=$i;
      $s=$s.$this->Encode()."&";
   }
   return $s;
}
//setters and getters
function getPattern(){
   return $this->Pattern;
}

function getPatternFlip(){
    return $this->Pattern;
}   
function getPattern(){
    return $this->Pattern;
}

//..etc

Example usage:

$o=new MyProtector($string,0,$pattern);
echo $o->$result; //returns encoded string
$o=new MyProtector($string,1,$pattern);
echo $o->$result; //returns decoded string
$o=new MyProtector($array,0,$pattern);
echo $o->$result; //returns decoded string with '&' inbetween encoded array entries
$o=new MyProtector($stringWithDelimiter,1,$pattern);
echo $o->$result;//returns decoded array

I'm sure there will be a few syntax errors, typos in there as I haven't compiled/tried the thing. Hope that helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!