PHP: How to break a UTF-8 string?

I have the following code that does not work with UTF-8 characters. How can i fix this?

$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 tried this code:

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

but it still does not work.

+3
source share
2 answers

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

 $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 fine.

+9
source

To work with UTF-8 strings, use Multibyte string functions .

For your purpose this 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]; } 
0
source

Source: https://habr.com/ru/post/1013965/


All Articles