开发者

PHP encoding to only have letters and numbers

Is there a encoding function in PHP which will encode string开发者_C百科s and the resulting output will only contain letters and numbers? I would use base64 but that still has some stuff which is not numeric/alphanumeric


You could use base32 (code easy to google), which is sort of a standard alternative to base64. Or resort to bin2hex() and pack("H*",$hex) to reverse. Hex encoding however leads to size doubling.


Short answer is no, base64 uses a reduced set of output chars compared with uuencode and was intended to solve most character converions issues - but still isn't url-safe (IIRC).

But the machanism is trivial and easily adapted - I'd suggest having a look at base32 encoding - same as base64 but using one less bit per input char to create the output (and hence a 32 char alphabet is all that's required) but using something different for the padding char ('=' is not url safe).

A quick google found this


Any of the hash functions (md5, sha1, etc.) output will only consist of hexadecimal digits but that's not exactly 'encoding'.


You could write your own base-62 encoder/decoder using a-z/A-Z/0-9. You'd need 3 digits for every ASCII character though, so not that efficient.


I wrote this to use letters, numbers and dashes.

I'm sure you can improve it to take out the dashes:

function pj_code($str) {
    $len = strlen($str);
    while ($len--) {
        $enc .= base_convert(ord(substr($str,$len,1)),10,36) . '-';
    }
    return $enc;
}


function pj_decode($str) {
    $ords = explode('-',$str);
    $c = count($ords);
    while ($c--) {
        $dec .= chr(base_convert($ords[$c],36,10));
    }
    return $dec;
}


You can use the basic md5 hash function which output only alphanumeric characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜