我在 php 中有一个像这样的字符串:
$string = "Count the character frequency of this string";
当我使用爆炸功能时,输出显示为:
Array (
[0] => Count
[1] => the
[2] => character
[3] => frequency
[4] => of
[5] => this
[6] => string
)
但是上面的输出并不让我满意,因为我想实现如下所示的输出:
Array (
[0] => C
[1] => o
[2] => u
[3] => n
[4] => t
[5] => t
[6] => h
[7] => e
[8] => c
[9] => h
[10] => a
[11] => r
[12] => a
[13] => c
...
)
我想分成单独的字母并省略空格。
str_split()
后使用 str_replace()
去除空格字符:
print_r(str_split(str_replace(' ', '', $string)));
如果您的字符串包含其他非字母数字字符,您可以使用正则表达式来替换所有非字母数字字符:
print_r(str_split(preg_replace('/[^\da-z]/i', '', $string)));
在一个函数调用中,将字符串拆分为零个或多个空格并省略任何空值。
代码:(演示)
$string = "Count the character frequency of this string";
var_export(
preg_split(
'/ */',
$string,
0,
PREG_SPLIT_NO_EMPTY
)
);
输出:
array (
0 => 'C',
1 => 'o',
2 => 'u',
3 => 'n',
4 => 't',
5 => 't',
6 => 'h',
7 => 'e',
8 => 'c',
9 => 'h',
10 => 'a',
11 => 'r',
12 => 'a',
13 => 'c',
14 => 't',
15 => 'e',
16 => 'r',
17 => 'f',
18 => 'r',
19 => 'e',
20 => 'q',
21 => 'u',
22 => 'e',
23 => 'n',
24 => 'c',
25 => 'y',
26 => 'o',
27 => 'f',
28 => 't',
29 => 'h',
30 => 'i',
31 => 's',
32 => 's',
33 => 't',
34 => 'r',
35 => 'i',
36 => 'n',
37 => 'g',
)
在 php 中默认可以将字符串作为字符数组访问
echo $string[0]
输出
C