gpt4 book ai didi

php - 如何逐字符拆分字符串,注意特殊字符

转载 作者:可可西里 更新时间:2023-11-01 00:49:36 25 4
gpt4 key购买 nike

我正在尝试逐个字符地展开字符串,但我在处理特殊字符时遇到了麻烦。我目前正在使用以下功能:

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

这是输出:

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] => ? )

换行符也有同样的问题:

输入:
“嘿!
Oui?”

输出:

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

有没有人能解决这个问题?非常感谢。

最佳答案

str_split 存在 Unicode 字符串问题。

您可以在 preg_split 中使用 u 修饰符

例如:

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

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

会输出

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] => ? )

关于php - 如何逐字符拆分字符串,注意特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10373022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com