我是新来的,我有一个问题。我正在做一个我很快就会使用的代码,更多的东西给我带来了巨大的疑问。所以我把更多特殊字符分开的单词分开,我希望他们能聚在一起为每个人分配颜色然后有什么方法可以做到这一点吗?
代码:
<?php
$text = "My nickname is: п€Яd Øwп€d"; #this would be the result of what i received via post
print_r(str_split($text));
?>
结果:
Array
(
[0] => M
[1] => y
[2] =>
[3] => n
[4] => i
[5] => c
[6] => k
[7] => n
[8] => a
[9] => m
[10] => e
[11] =>
[12] => i
[13] => s
[14] => :
[15] =>
[16] => &
[17] => #
[18] => 1
[19] => 0
[20] => 8
[21] => 7
[22] => ;
[23] => &
[24] => e
[25] => u
[26] => r
[27] => o
[28] => ;
[...]
)
我想回复一下:
Array ( [0] => M
[1] => y
[2] =>
[3] => n
[4] => i
[5] => c
[6] => k
[7] => n
[8] => a
[9] => m
[10] => e
[11] =>
[12] => i
[13] => s
[14] => :
[15] =>
[16] => п
[17] => €
[...]
)
感谢您的帮助。
[增订]
我测试了朋友们已经通过的功能,大部分不使用utf-8作为我的默认字符集ISO-8859-1,还有一件事我忘记添加,通过编辑短语“我的昵称是:”和添加&amp;例如:“我的昵称是&amp;个人名称”返回一个错误。我很感激谁能再次帮助。
答案 0 :(得分:1)
您可以尝试编写自己的str_split
,其外观如下所示
function str_split_encodedTogether($text) {
$result = array();
$length = strlen($text);
$tmp = "";
for ($charAt=0; $charAt < $length; $charAt++) {
if ($text[ $charAt ] == '&') {//beginning of special char
$tmp = '&';
} elseif ($text[ $charAt ] == ';') {//end of special char
array_push($result, $tmp.';');
$tmp = "";
} elseif (!empty($tmp)) {//in midst of special char
$tmp .= $text[ $charAt ];
} else {//regular char
array_push($result, $text[ $charAt ]);
}
}
return $result;
}
它的作用基本上是检查当前字符是否为&
,如果是,请将$tmp
中的所有后续字符(包括&符号)保存到;
。这基本上为您提供了想要的结果,但只要有&
不属于编码字符,它就会失败。
答案 1 :(得分:0)
使用preg_split()
:
<?php
$text = "My nickname is: п€Яd Øwп€d"; #this would be the result of what i received via post
print_r(preg_split('/(\&(?=[^;]*\s))|(\&[^;]*;)|/', $text, -1, PREG_SPLIT_DELIM_CAPTURE + PREG_SPLIT_NO_EMPTY));
?>