Home > PHP > Encode String to Only Alphanumeric Chars

Encode String to Only Alphanumeric Chars

November 27th, 2014 Leave a comment Go to comments

If you need to encode a string with all sorts of problem characters into a URL-safe string, urlencode() is not right solution.

What you need is a function that will give you only numbers and letters. No %’s or &’s, spaces, or any other non-alphanumeric character.

For this we will use PHP’s bin2hex() function, and its pack() function.

For example, it can convert: “(!X>4Ob=h/&hN\'” into this much nicer string: “2821583e344f623d682f26684e5c27”.

Here are the functions you need:

function hex_encode($string)
{
    return bin2hex($string);
}

function hex_decode($string)
{
    return pack("H*", $string);
}
Categories: PHP Tags:
  1. No comments yet.
  1. No trackbacks yet.