文字列を単一文字の文字列の配列に分割し、分割された文字の数を取得する必要があります。
たとえば、「文字」を分割すると、配列が得られ"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)
}
等
php関数str_splitを使用します。例は次のとおりです。
$array = str_split("cat");
使用するstr_split
$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.
ここでexplodeを使用してドキュメントを作成します
/* 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 ) );