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!
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,
Here is the part that does the work. In one line.
Explanation: The first part is self-explanatory. The second part is the length of the string without the characters in the
$needlestring. This is done by replacing each occurrences of any characters inside the$needlewith a blank string.To do this, we split
$needleinto an array, once character for each item, usingstr_split. Then pass it tostr_replace. It replaces each occurence of any items in the$searcharray with a blank string.Echo it out,
you get: