使用文本分隔符计算字符串内特定字符的数量

I have string:

$output = "Program: First 0 0 0 0 0 0 0 Program: Second 0 0 0 0 0 Program: Third 0 0 0 0 0 0 0 0";

I need this output:

$output = "Program: First 7 Program: Second 5 Program: Third 8";

I know i can count all "0" occurences with "substr_count", but how i can count specific group of zeros before text "Program"?

This would exactly output what you need. Its not that beautiful, u might find a better solution with google, but that just came into my mind:

<?php

$output = "Program: First 0 0 0 0 0 0 0 Program: Second 0 0 0 0 0 Program: Third 0 0 0 0 0 0 0 0";

$output = explode("Program:", $output);
array_splice($output, 0,1 );
$endString = '';
foreach($output as $elem) {
    $count = substr_count($elem, "0");
    $elemWithoutZero = str_replace('0', '', $elem);
    $endString = $endString . 'Program: ' . $elemWithoutZero . $count . ' ';
}
var_dump($endString);


?>

Output:

string(74) "Program: First 7 Program: Second 5 Program: Third 8" 

Anyways if you get that kind of data, you might find a better solution at the place where you create that data.

substr_count can be provided a maximum length to count till. Simply use strpos to find the index of "Second" and count the 0's to that index. You can also provide 'substr_count' with an offset, so start at the offset for the next range of zeroes.

substr_count Documentation

Can do this:

$output = "Program: First 0 0 0 0 0 0 0 Program: Second 0 0 0 0 0 Program: Third 0 0 0 0 0 0 0 0";
$pieces = explode('Program',$output);
foreach($pieces as $piece){
   echo substr_count($piece, '0').PHP_EOL;
}

Output:

0
7
5
8

Other way:

$programs = Array('First','Second','Third');
$output = "Program: First 0 0 0 0 0 0 0 Program: Second 0 0 0 0 0 Program: Third 0 0 0 0 0 0 0 0";
$pieces = explode(' Program:',$output);
$looutput = '';
$i = 0;
foreach($pieces as $piece){
   $loutput .= 'Program: '.$programs[$i].' '.substr_count($piece, '0').' ';
   $i++;
}
echo $loutput;

Output:

Program: First 7 Program: Second 5 Program: Third 8