开发者

How to safely encode PHP string into alphanumeric only?

How to safely encode PHP s开发者_开发知识库tring into alphanumeric only string? E.g. "Hey123 & 5" could become "ed9e0333" or may be something better looking It's not about stripping characters, its about encoding.

The goal is to make any string after this encoding suitable for css id string (alnum), but later I will need to decode it back and get the original string.


bin2hex seems to fit the bill (although not as compact as some other encodings). Also take care that CSS ids cannot start with a number, so to be sure you'll need to prefix something to the bin2hex result before you have your final ID.

For the reverse (decoding), there's no such thing as hex2bin, but someone on the PHP documentation site suggested this (untested):

$bin_str = pack("H*" , $hex_str);


You can use BASE64 encoding

http://php.net/manual/function.base64-encode.php


This thread is dead for long time, but I was looking for solution to this problem and found this thread, someone might find the easy answer useful.

My solution is:

str_replace('=', '_', base64_encode($data));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜