echo "There are " . substr_count($string, 'K') . " K in the string";
If you do not want to count K-1 , it could be:
echo "There are " . substr_count($string, 'K')-substr_count($string, 'K-') . " K in the string";
To solve a new problem in the comments:
$string = '01122028K,02122028M,02122028K-1,02122028K-2,03122028K,04122028M,05122028K-1,04122028M,05122028K,06122028P-2,07122028K,08122028P-'; preg_match_all('/K(?:-\d+)?/', $string, $match); $counts = array_count_values($match[0]); print_r($counts); Array ( [K] => 4 [K-1] => 2 [K-2] => 1 )
source share