Thursday, 1 September 2016

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

function count_occurences($char_string, $haystack, $case_sensitive = true){
    if($case_sensitive === false){
        $char_string = strtolower($char_string);
        $haystack = strtolower($haystack);
    }

    $characters = str_split($char_string);
    $character_count = 0;
    foreach($characters as $character){
        $character_count = $character_count + substr_count($haystack, $character);
    }
    return $character_count;
}
To use;
$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
print count_occurences($needle, $haystack);
You can set the third parameter to false to ignore case.

0 comments:

Post a Comment