tags:

views:

194

answers:

2

How to safely encode PHP string 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.

+1  A: 

You can use BASE64 encoding

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

Benoit Vidis
After base64_encode there is '=' character in the end of string, not 100% alphanumeric
PHP thinker
+1  A: 

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);
Wim