如果我有这样的字符串:
Run Code Online (Sandbox Code Playgroud)$string = '01122028K,02122028M,03122028K,04122028M,05122028K,06122028P-2,07122028K,08122028P-';
如何在字符串$ string中获取'K'的数量.在这种情况下,K将是4.我知道它可以通过帮助strpos()在将$ string分解为数组之后通过循环来解决.有任何PHP功能以直截了当的方式完成吗?
谢谢.
echo "There are " . substr_count($string, 'K') . " K's in the string";
Run Code Online (Sandbox Code Playgroud)
如果你不想数K-1这个可以是:
echo "There are " . substr_count($string, 'K')-substr_count($string, 'K-') . " K's in the string";
Run Code Online (Sandbox Code Playgroud)
要在评论中解决新问题:
$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
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |