0

如果我有这样的字符串:

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

如何获取字符串$string 中“K”的数量。在这种情况下,K 将为 4。我知道它可以通过帮助 strpos() 在将 $string 分解为数组后的循环中解决。是否有任何 php 函数可以直接执行此操作?

谢谢你。

4

2 回答 2

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

如果您不想计算K-1,可以是:

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

要解决评论中的新问题:

$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
)
于 2013-04-23T03:15:51.163 回答
0

也试试这个解决方案:

$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++:
}

然后...

echo $count;

这不是一种“直截了当的方式”,但我发现它很有用,因为它非常灵活,您可以操作字符串上的所有类型的代码。

祝你好运!

于 2013-04-23T03:19:24.877 回答