Encode a PHP String

Today I updated PHPMyadmin on one of my boxes. Nothing special so far, but I saw that it’s now possible to export data in form of a PHP array. Well I thought that’s somehow nice. But the plugin was broken. Encoding done wrong.

So I jumped in for a fix. The heart of it is to encode a string properly, so to say, replace all control chars and those after x7D. Then ” $ and \ needs to be slash-encoded additionally.

I choose to encounter it with the underrated for-loop language construct:

/**
 * Encode String as PHP Code
 *
 * @param string $s string to encode
 * @return string Double Quoted PHP String value, single lined, US-
 *         ASCII, control chars hex-encoded.
 */
function StringEncode($s) {
    for(
        $r = '"',
        $l = strlen($s),
        $i = 0
        ;
        $i < $l
        ;
        $c = $s[$i++],
        $o = ord($c),
        $b = $o > 31 && $o < 127,
        $b && ($o == 34 || $o == 36 || $o == 92) && $c = '\\'.$c,
        $r.= $b ? $c : '\x'.strtoupper(substr('0'.dechex($o),-2))
    );
    return $r.'"';
}

I didn’t name the vars properly, so here some translation table: s – string, r – result, l – length, i – iterator, c – char, o – ord, b – bare. Expand names on wish. I’m pretty sure there are many ways to solve the problem, this is just one approach. But please feel free to share your ideas in comments.

This entry was posted in Pressed and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s