Wrote function, takes 2 parameters: $phone
- can be either a string or an array of strings $patter
- a template under which strings will be changed
The essence of the function, to bring the format of the lines (phone numbers) in the format specified in the pattern ( $pattern
)
# Pattern format "# (###) ###-##-##" function PhoneFormat($phone, $pattern = "# (###) ###-##-##") { if(is_array($phone)) { foreach ($phone as &$item) { $item = PhoneFormat($item, $pattern); } return $phone; } else { $phone = preg_replace("/[^0-9]/", "", $phone); if(substr_count($pattern, "#") != strlen($phone)) return false; for($i = 0, $k = 0; $i < strlen($pattern); $i++) { if($pattern[$i] == "#") $pattern[$i] = $phone[$k++]; } } return $pattern; }
How do you like the algorithm in terms of efficiency and implementation? Was it right to use recursion?