gpt4 book ai didi

php - 如何在PHP中拆分汉字?

转载 作者:行者123 更新时间:2023-12-04 21:24:09 26 4
gpt4 key购买 nike

我需要一些关于如何在 PHP 中拆分与英文单词和数字混合的汉字的帮助。

例如,如果我阅读

FrontPage 2000中文版應用大全

我希望得到

FrontPage, 2000, 中,文,版,應,用,大,全

FrontPage, 2,0,0,0, 中,文,版,應,用,大,全

我怎样才能做到这一点?

提前致谢:)

最佳答案

假设您使用的是 UTF-8(或者您可以使用 Iconv 或其他工具将其转换为 UTF-8),然后使用 u 修饰符(文档:http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php)

<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/./u', $s, $matches));
echo "\n";
print_r($matches);
?>

会给予

21
Array
(
[0] => Array
(
[0] => F
[1] => r
[2] => o
[3] => n
[4] => t
[5] => P
[6] => a
[7] => g
[8] => e
[9] =>
[10] => 2
[11] => 0
[12] => 0
[13] => 0
[14] => 中
[15] => 文
[16] => 版
[17] => 應
[18] => 用
[19] => 大
[20] => 全
)

)

请注意,我的源代码也存储在以 UTF-8 编码的文件中,因为 $s 包含这些字符。

以下将匹配字母数字作为一个组:

<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/(\w+)|(.)/u', $s, $matches));
echo "\n";
print_r($matches[0]);
?>

结果:

10
Array
(
[0] => FrontPage
[1] =>
[2] => 2000
[3] => 中
[4] => 文
[5] => 版
[6] => 應
[7] => 用
[8] => 大
[9] => 全
)

关于php - 如何在PHP中拆分汉字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4113802/

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