How to split a line character by character, paying attention to special characters

I am trying to blow a string character by character, but I have problems with special characters. I am currently using the following function:

<?php
$input = "Comment ça va?";
$array_input = str_split($input, 1);
print_r($array_input);
?>

Here's the conclusion:

Array (
[0] => C [1] => o [2] => m [3] => m [4] => e
[5] => n [6] => t [7] => [8] =>   [9] =>  
[10] => a [11] => [12] => v [13] => a [14] => ? )

I have the same problem with line break:

Input:
"Hé!
Oui?"

Conclusion:

Array ( [0] => H [1] =>   [2] =>   [3] => ! [4] => 
[5] => [6] => O [7] => u [8] => i [9] => ? )

Does anyone have a solution to this problem? Many thanks.

+3
source share
2 answers

str_split has problems with Unicode strings.

You can use the modifier uin preg_splitinstead

For instance:

$input = "Comment ça va?";
$letters1 = str_split($input);
$letters2 = preg_split('//u', $input, -1, PREG_SPLIT_NO_EMPTY);

print_r($letters1);
print_r($letters2);

Will output

Array ( [0] => C [1] => o [2] => m [3] => m [4] => e 
        [5] => n [6] => t [7] => [8] =>   [9] =>   
        [10] => a [11] => [12] => v [13] => a [14] => ? ) 

Array ( [0] => C [1] => o [2] => m [3] => m [4] => e 
        [5] => n [6] => t [7] => [8] => ç [9] => a 
        [10] => [11] => v [12] => a [13] => ? ) 
+3
source

, PHP str_split , .. . , str_split

function mb_str_split( $string ) { 
    # Split at all position not after the start: ^ 
    # and not before the end: $ 
    return preg_split('/(?<!^)(?!$)/u', $string ); 
} 

(: PHP)

+2

All Articles