Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

if I have a string something like this:

$string = '01122028K,02122028M,03122028K,04122028M,05122028K,06122028P-2,07122028K,08122028P-';

How can I do to get the number of 'K' inside string $string. In this case K would be 4. I know it can be solved by the help strpos() through out the looping after explode the $string into array. Is any php function to do it in straightforward way?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

echo "There are " . substr_count($string, 'K') . " K's in the string";

If you don't want to count K-1 this can be:

echo "There are " . substr_count($string, 'K')-substr_count($string, 'K-') . " K's in the string";

To solve the 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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...