我需要将 String 拆分为单个字符 Strings 的数组并获取拆分字符的计数。
例如,拆分“字符”将给出数组"c", "h", "a", "r", "a", "c", "t", "e", "r"
。
编辑
是否可以使用内置函数计算拆分的字符串字符?
Array ( [c] => 2 [h] => 1 [a] => 2 [r] => 2 [t] => 1 [e] => 1 )
[阵列$array
$array = str_split('Cat');
拆分str_split()
后将如下所示:
ARRAY
{
[0] = 'C'
[1] = 'a'
[2] = 't'
}
回答已编辑的问题
是的,您可以使用该功能count_chars()
$str = "CHARACTERS";
$array = array();
foreach (count_chars($str, 1) as $i => $val) {
array[] = array($str, $i);
}
将输出以下内容:
ARRAY
{
[0] = ARRAY("C" => 2)
[1] = ARRAY("H" => 1)
}
ETC
使用 php 函数str_split,示例如下:
$array = str_split("cat");
$array = str_split("cat");
尝试count_chars
:
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
上面的示例将输出:
There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.
在此处使用爆炸文档
/* A string that doesn't contain the delimiter will simply return a one-length array of the original string. */
$input1 = "hello";
$input2 = "hello,there";
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );