How the character code in PHP

Discussion in 'PHP' started by redhits, Sep 18, 2007.

  1. #1
    I known i can get the ASCII code of an character using ord() but i want to encode a string like %45,%20, so i need the HEX code or however it's called
     
    redhits, Sep 18, 2007 IP
  2. sea otter

    sea otter Peon

    Messages:
    250
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #2
    sea otter, Sep 18, 2007 IP
  3. redhits

    redhits Notable Member

    Messages:
    3,023
    Likes Received:
    277
    Best Answers:
    0
    Trophy Points:
    255
    #3
    that do not encrypt the string, only the special characters from the string!
     
    redhits, Sep 19, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    This should do what you want.

    
    function str_to_hex($string)
    {
    	$hex = '';
    	$len = strlen($string);
    	
    	for ($i = 0; $i < $len; $i++)
    	{
    		$hex .= '%' . str_pad(dechex(ord($string[$i])), 2, 0, STR_PAD_LEFT);
    	}
    	
    	return $hex;
    }
    
    PHP:
     
    nico_swd, Sep 19, 2007 IP
  5. redhits

    redhits Notable Member

    Messages:
    3,023
    Likes Received:
    277
    Best Answers:
    0
    Trophy Points:
    255
    #5
    One more question , how i can do the reverse of this!?
     
    redhits, Sep 21, 2007 IP
  6. sea otter

    sea otter Peon

    Messages:
    250
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #6
    In keeping with nico's scheme of things :)

    
    function hex_to_str($hex)
    {
    	$string = '';
    	$data = explode('%',$hex);
    	$len = count($data);
    	for ($i=1; $i < $len; $i++)	// yes, ONE.  skip first array element, which is empty
    			$string .= chr(hexdec($data[$i]));
    	return $string;
    }
    
    PHP:
     
    sea otter, Sep 21, 2007 IP