Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP count of occurrences of characters of a string within another string

Let's say I have two strings.

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

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).

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

Thanks in advance!

like image 318
arik Avatar asked Jan 19 '11 13:01

arik


People also ask

What is Substr_count function in PHP?

The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., “abc” substring is not present in the string “Abcab”.

How do you count occurrences of a given character in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do I count characters in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

How do you find the number of substrings in a string?

Total number of substrings = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1. So now we have a formula for evaluating the number of substrings where n is the length of a given string.


1 Answers

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.

Basically,

$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));

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.

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.

Echo it out,

echo "Count = $count\n";

you get:

Count = 5

like image 152
Thai Avatar answered Sep 29 '22 18:09

Thai