首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在php中将字符串拆分为字符串数组和拆分字符数。

在php中将字符串拆分为字符串数组和拆分字符数。
EN

Stack Overflow用户
提问于 2013-02-09 14:33:47
回答 5查看 1K关注 0票数 1

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

分裂“字符”将给数组"c", "h", "a", "r", "a", "c", "t", "e", "r"

编辑

是否可以使用内置函数获得计数分裂的字符串字符?

代码语言:javascript
复制
Array ( [c] => 2 [h] => 1 [a] => 2 [r] => 2 [t] => 1 [e] => 1 ) 
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-02-09 14:36:15

使用str_split

代码语言:javascript
复制
$array = str_split("cat");

试试count_chars

代码语言:javascript
复制
<?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";
}
?>

上面的示例将输出:

代码语言:javascript
复制
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.
票数 2
EN

Stack Overflow用户

发布于 2013-02-09 14:36:38

[ $array ]

代码语言:javascript
复制
$array = str_split('Cat');

str_split() 拆分后的将如下所示:

代码语言:javascript
复制
ARRAY
{
   [0] = 'C'
   [1] = 'a'
   [2] = 't'
}

对编辑问题的回答

是的,您可以使用函数count_chars()

代码语言:javascript
复制
$str = "CHARACTERS";

$array = array();

foreach (count_chars($str, 1) as $i => $val) {
   array[] = array($str, $i);
}

将输出以下内容:

代码语言:javascript
复制
ARRAY
{
   [0] = ARRAY("C" => 2)
   [1] = ARRAY("H" => 1)
}

票数 4
EN

Stack Overflow用户

发布于 2013-02-09 14:35:28

使用php函数拆分,这里的示例如下:

代码语言:javascript
复制
$array = str_split("cat");
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14789153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档