Skip to content

Instantly share code, notes, and snippets.

@artlung
Last active January 1, 2026 04:47
Show Gist options
  • Select an option

  • Save artlung/b2992e8e763123621df634ccc067f118 to your computer and use it in GitHub Desktop.

Select an option

Save artlung/b2992e8e763123621df634ccc067f118 to your computer and use it in GitHub Desktop.
/**
*
* Replaces sequences of repeated numeric characters in a string with the length of that sequence.
*
* @param $inputString string A string of numeric characters
* @param $numberToReplaceWithLengthsOf int A single digit (0-9)
*
*/
function replaceRepeats(string $inputString, int $numberToReplaceWithLengthsOf): string
{
$length = strlen($inputString);
$resultString = '';
$bufferedCountOfRepeats = 0;
for ($i = 0; $i < $length; $i++) {
$currentChar = $inputString[$i];
$currentChatAsInt = intval($currentChar);
if ($currentChatAsInt === $numberToReplaceWithLengthsOf && $bufferedCountOfRepeats) {
$bufferedCountOfRepeats++;
} elseif ($currentChatAsInt === $numberToReplaceWithLengthsOf && !$bufferedCountOfRepeats) {
$bufferedCountOfRepeats = 1;
} elseif ($currentChatAsInt !== $numberToReplaceWithLengthsOf && $bufferedCountOfRepeats) {
$resultString = $resultString . strval($bufferedCountOfRepeats);
$bufferedCountOfRepeats = 0;
$resultString = $resultString . $currentChar;
} else {
$resultString = $resultString . $currentChar;
}
}
if ($bufferedCountOfRepeats) {
$resultString = $resultString . strval($bufferedCountOfRepeats);
}
return $resultString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment