Get Sepecific String Inside String Number

if I have a line something like this:

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

How can I do to get the number "K" inside the string $ string. In this case, K will be 4. I know that this can be solved with strpos () a loop after the string $ explodes into an array. Is any php function to do this in an easy way?

Thanks.

0
source share
2 answers
 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 ) 
+6
source

Try this solution as well:

 $string = '01122028K,02122028M,03122028K,04122028M,05122028K,06122028P-2,07122028K,08122028P-'; $strlen = strlen($string); $count = 0; for( $i = 0; $i <= $strlen; $i++ ) { $char = substr( $string, $i, 1 ); // $char contains the current character, so do your processing here if ($char == "K") $count++: } 

then ...

 echo $count; 

This is not a β€œsimple way”, but I found it useful as it is very flexible and you can manipulate all types of code in your line.

Good luck

0
source

All Articles