1

I have this some code that will auto generate a string but some of the special characters is shown like: �

Code:

header("Content-type: text/html; charset=utf-8");
function RandomString($length = 10){
    $chars ='0123456789abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ!#¤%&()=?@£$€{}[]+';
    $randString = '';
    for($i = 0; $i < $length; $i++){
        $randString .= $chars[rand(0, 88)];
    }
    echo $randString;
    return $randString;
}
7
  • 1
    Are you trying to "Encode" "Encrypt" or "Hash" the string.. there is a big difference between the three. Commented Jan 25, 2015 at 18:10
  • 2
    @OrelEraki how do you think that function is meant to encrypt or hash something? Clearly, this is a question about character encoding. Commented Jan 25, 2015 at 18:17
  • php has no notion of your string being a string with utf8 characters - A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. - see php.net/manual/en/language.types.string.php and especially the details of the string type. Commented Jan 25, 2015 at 18:17
  • 2
    The encoding of your source file must also be UTF-8 to work this code. And you should use special "Unicode" function to extract i-th character from string (cause some characters requires two or more bytes). Commented Jan 25, 2015 at 18:18
  • 1
    @OrelEraki the function is called RandomString. Guess what it does. Commented Jan 25, 2015 at 18:34

1 Answer 1

3

There are a few characters in your $chars array, that are multibyte characters (UTF-8 to be precise). Unfortunately, PHP doesn't handle multibyte characters that well on its own.

A solution here, is to replace all the calls with a variant that supports multibyte characters. The mbstring extension provides such support.

You can replace a call as $chars[rand(0,88)] by a call to the mb_substr function. So you get something like mb_substr($chars, rand(0, 88), 1).

Sign up to request clarification or add additional context in comments.

1 Comment

mb_substr($chars, rand(0,88),1,'utf8'); made the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.