2015-05-07

PHP decode C string-like encoded string

Views: 5819 | Add Comments

To decode string encoded in C string-like to what it exactly was in memory, I write a PHP function.

C string-like encoded string as like this:

\r\n\x90

The PHP function, unescape C string.

function unescape_c_str($str){
    $ret = '';
    $len = strlen($str);
    for($i=0; $i<$len; $i++){
        if($str[$i] != '\\'){
            $ret .= $str[$i];
            continue;
        }
        $i++;
        switch($str[$i]){
            case 's':
                $ret .= ' ';
                break;
            case 'a':
                $ret .= "\a";
                break;
            case 'b':
                $ret .= "\b";
                break;
            case 'f':
                $ret .= "\f";
                break;
            case 'v':
                $ret .= "\v";
                break;
            case 'r':
                $ret .= "\r";
                break;
            case 'n':
                $ret .= "\n";
                break;
            case 't':
                $ret .= "\t";
                break;
            case '\\':
                $ret .= "\\";
                break;
            case 'x':
                $hex = substr($str, $i+1, 2);
                $ret .= hex2bin($hex);
                $i += 2;
                break;
            default:
                $ret .= $str[$i];
                break;
        }
    }
    return $ret;
}
Posted by ideawu at 2015-05-07 12:54:20

Leave a Comment