Encode Any String to Only Alphanumeric Chars - Better Than URLEncode

Have you ever been faced with a situation (in PHP) of needing to pass information in a URL (or a JSON object, XML, etc), but for whatever reason, urlencode() won't do the job? For example, if you want to base64_encode() a string, then pass it in a URL. Since base64 includes URL-unsafe characters like +/-=, you have to jump through hoops to make it work.

However, there is an easier way, that produces only letters and numbers; no symbols or punctuation of any kind.  Yes, it will inflate the length of the string a little more, but it might be what you need.

Here are the two functions to encode and then decode:

function hex_encode($input) {
  return bin2hex($input);

function hex_decode($input) {
  return pack("H*", $input);

You can convert a tricky string like this: 


Into a URL, MySQL, JSON, XML, etc.- safe string like this:


Hope this helps!