0

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"?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@user2337706 I hope you'r understanding what happens there, so you can write it yourself next time :)
Yes i will analyze it. I don't like to disturb people, but sometime i can spend hours to write so simple code)
2

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

3 Comments

not bad, but it doesn't saves Program: First, Second for current output.
Your question was "how can i count specific group of zeros before text Program" then I thought knowing the amount of zeros, do know the replacement.
Yes, but it seems to me that the response of @Xatenev is better.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.