Encode Any String to Only Alphanumeric Chars - Better Than URLEncode
Submitted by admin on Mon, 02/26/2024 - 7:13pm
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:
(!X>4Ob=h/&hN\'
Into a URL, MySQL, JSON, XML, etc.- safe string like this:
2821583e344f623d682f26684e5c27
Hope this helps!