Created
May 24, 2020 11:51
-
-
Save Alexfilus/a40aa7f737032ead271b0f25a2581102 to your computer and use it in GitHub Desktop.
print range to count and array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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