将字符串拆分为字符串数组和php中所选字符的数量

时间:2013-02-09 14:33:47

标签: php arrays string split

我需要将一个String拆分成一个单字符串的数组,并获得分裂的字符数。

例如,分裂"字符"会给出数组"c", "h", "a", "r", "a", "c", "t", "e", "r"

编辑

是否可以使用内置函数获取计数拆分字符串字符?

Array ( [c] => 2 [h] => 1 [a] => 2 [r] => 2 [t] => 1 [e] => 1 ) 

5 个答案:

答案 0 :(得分:4)

[数组$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)
}

答案 1 :(得分:2)

使用php函数str_split, 例如:

$array = str_split("cat");

答案 2 :(得分:2)

使用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.

答案 3 :(得分:1)

您需要使用str_split

即。

$array = str_split($str, 1);

答案 4 :(得分:-1)

使用爆炸doc

 /* 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 ) );