Skip to content

Instantly share code, notes, and snippets.

@Alexfilus
Created May 24, 2020 11:51
Show Gist options
  • Save Alexfilus/a40aa7f737032ead271b0f25a2581102 to your computer and use it in GitHub Desktop.
Save Alexfilus/a40aa7f737032ead271b0f25a2581102 to your computer and use it in GitHub Desktop.
print range to count and array
/**
* @param string $range
* @return string
*/
public static function cleanRange(string $range): string
{
return preg_replace('/[^0-9\-,]/', '', $range);
}
/**
* @param string $strRange
* @return array
*/
public static function rangeToArray(string $strRange): array
{
$result = [];
$strRange = self::cleanRange($strRange);
$arRanges = explode(',', $strRange);
foreach ($arRanges as $range) {
if (strpos($range, '-') === false) {
$result[$range] = $range;
} else {
[$first, $second] = explode('-', $range);
foreach (range($first, $second) as $val) {
$result[$val] = $val;
}
}
}
return $result;
}
/**
* @param string $strRange
* @return int
*/
public static function rangeToCount(string $strRange): int
{
return count(self::rangeToArray($strRange));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment