DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Str_hex And Hex_str

  • submit to reddit
        // Convert hex to string and vice versa.
// (Source:

function str_hex($string){
    for ($i=0; $i < strlen($string); $i++){
        $hex .= dechex(ord($string[$i]));
    return $hex;

function hex_str($hex){
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    return $string;

// example:

$hex = str_hex("test sentence...");
// $hex contains 746573742073656e74656e63652e2e2e

print hex_str($hex);
// outputs: test sentence...