Created
November 24, 2018 00:54
-
-
Save davidon/6ae2c0707ea060316da09f801aeb2b95 to your computer and use it in GitHub Desktop.
Format phone number which contains spaces and dashes into every three numbers separated by dashes
This file contains hidden or 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
public function format_phone_number($S) { | |
$S = str_replace(' ', '', $S); | |
$S = str_replace('-', '', $S); | |
$len = strlen($S); | |
$num_groups = floor($len / 3); | |
$remain = $len % 3; | |
if ($num_groups >= 1 && $remain == 1) { | |
$num_groups -= 1; | |
$remain += 3; //4 | |
} | |
if ($num_groups === 0) { | |
return $S; | |
} | |
$str_result = ''; | |
$result = array(); | |
for ($i = 0; $i < $num_groups; $i++) { | |
$index_min = $i * 3; | |
$s_sub = substr($S, $index_min, 3); | |
$result[] = $s_sub; | |
} | |
if ($remain !== 0) { | |
$s_remain = substr($S, $num_groups * 3, $remain); | |
if ($remain < 3) { | |
$result[] = $s_remain; | |
} else { | |
$result[] = substr($s_remain, 0, 2); | |
$result[] = substr($s_remain, 2, 2); | |
} | |
} | |
$str_result = implode('-', $result); | |
return $str_result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Task:
A raw phone number might include spaces and dashes; Spaces are to be removed; and every three numbers are to be separated by one dash; The last segment can have 1 or 2 numbers; If there are 4 numbers contained in the two last segments, then two numbers are placed for each of the last two segments.