7

I have the following code which is not working with UTF-8 characters. How can I fix it?

$seed = preg_split('//u', $seed, -1, PREG_SPLIT_NO_EMPTY);
$seed = str_split('АБВГДЕЖЗ'); // and any other characters

shuffle($seed); // probably optional since array_is randomized; this may be redundant
$code = '';
foreach (array_rand($seed, 5) as $k) $md5_hash .= $seed[$k];

//We don't need a 32 character long string so we trim it down to 5 
$security_code = $code;

I have tried this code:

$seed = preg_split('//u', $seed, -1, PREG_SPLIT_NO_EMPTY);

but it is still not working.

2
  • 2
    When I enter PHP str_split UTF-8 into Google, I get a very good result on the #1 position. Commented Feb 8, 2014 at 23:23
  • 1
    @Pekka웃 when I do that now, I get this question Commented Apr 11, 2017 at 14:07

2 Answers 2

14

You must create the variable $seed and give it a string value before you can use it as the second parameter of preg_split:

$seed = 'АБВГДЕЖЗ';
$seed = preg_split('//u', $seed, -1, PREG_SPLIT_NO_EMPTY);

The output of print_r($seed) will be:

Array
(
    [0] => А
    [1] => Б
    [2] => В
    [3] => Г
    [4] => Д
    [5] => Е
    [6] => Ж
    [7] => З
)

I hope the rest of your code will work just fine.

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

1 Comment

It is not necessary to pass string into preg_split as variable. Function does not require this. It can be string to.
1

For working with UTF-8 strings use Multibyte String Functions.

For your purpose it will be mb_split.

Update

$seed = preg_split('//u', 'abcdefghijklmnopqrstuvwxyz', -1, PREG_SPLIT_NO_EMPTY);
foreach (array_rand($seed, 5) as $k) {
    $md5_hash .= $seed[$k];
}

8 Comments

Thanks, but this not working $seed = mb_split('АБВГДЕЖЗ'); // and any other characters
Do your have php module extension=php_mbstring.dll enabled?
Yes. I don't understand how the code with this function has to look.
Something like this mb_split("\s", "hello world")
In your case it should be mb_split("//", "АБВГДЕЖЗ")
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.