PHP计数字符串在另一个字符串中出现的字符数 [英] PHP count of occurrences of characters of a string within another string

查看:94
本文介绍了PHP计数字符串在另一个字符串中出现的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个字符串。

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

我想计算 $ needle 发生在 $ haystack 中。在 $ haystack 中,有字符'A'(两次),'X','Y'和'Z',所有这些都在针结果应该是5(区分大小写)。

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

在PHP中有没有任何函数,或者我必须自己编程吗?

Is there any function for that in PHP or do I have to program it myself?

提前感谢!

推荐答案

可以计算原始字符串的长度和长度的字符串没有这些字符。

You can calculate the length of the original string and the length of the string without these characters. The differences between them is the number of matches.

基本上,

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

这是工作的部分。一行。

Here is the part that does the work. In one line.

$count = strlen($haystack) - strlen(str_replace(str_split($needle), '', $haystack));

说明:第一部分是不言自明的。第二部分是在 $ needle 字符串中没有字符的字符串的长度。这是通过用空白字符串替换 $ needle 中的每个字符的每个出现来完成的。

Explanation: The first part is self-explanatory. The second part is the length of the string without the characters in the $needle string. This is done by replacing each occurrences of any characters inside the $needle with a blank string.

,我们使用 $ needle 拆分为一个数组,每个项目一次为字符> str_split 。然后将其传递到 str_replace 。它用一个空白字符串替换 $ search 数组中任何项目的每一个。

To do this, we split $needle into an array, once character for each item, using str_split. Then pass it to str_replace. It replaces each occurence of any items in the $search array with a blank string.

/ p>

Echo it out,

echo "Count = $count\n";

您会得到:


Count = 5

这篇关于PHP计数字符串在另一个字符串中出现的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆