我需要一些关于如何在PHP中拆分混合了英文单词和数字的中文字符的帮助。
例如,如果我读到
FrontPage 2000中文版應用大全我希望能得到
FrontPage, 2000, 中,文,版,應,用,大,全或
FrontPage, 2,0,0,0, 中,文,版,應,用,大,全我如何才能做到这一点?
提前感谢:)
发布于 2010-11-07 00:09:12
假设您正在使用UTF-8 (或者您可以使用图标或其他工具将其转换为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] => 全
)发布于 2017-05-10 09:58:43
/**
* Reference: http://www.regular-expressions.info/unicode.html
* Korean: Hangul
* CJK: Han
* Japanese: Hiragana, Katakana
* Flag u required
*/
preg_match_all(
'/\p{Hangul}|\p{Hiragana}|\p{Han}|\p{Katakana}|(\p{Latin}+)|(\p{Cyrillic}+)/u',
$str,
$result
);如果你使用的也是PHP7.0,这个也可以用。
这个不起作用。我很抱歉我支持了一个不可行的解决方案...
<?
$s = "FrontPage 2000中文版應用大全";
print_r(preg_match_all('/(\w+)|(.)/u', $s, $matches));
echo "\n";
print_r($matches[0]);
?>发布于 2012-02-29 05:24:45
使用此代码,您可以使中文文本(utf8)在行尾换行,以使其仍然可读
print_r(preg_match_all('/([\w]+)|(.)/u', $str, $matches));
$arr_result = array();
foreach ($matches[0] as $key => $val) {
$arr_result[]=$val;
$arr_result[]="​"; //add Zero-Width Space
}
foreach ($arr_result as $key => $val) {
$out .= $val;
}
return $out;https://stackoverflow.com/questions/4113802
复制相似问题