Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to split a UTF-8 string?

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.

like image 908
user3288430 Avatar asked Feb 08 '14 23:02

user3288430


People also ask

How to split a string in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

What is split function in PHP?

PHP - Function split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.


1 Answers

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.

like image 115
Sharanya Dutta Avatar answered Sep 21 '22 23:09

Sharanya Dutta