3v4l.org

run code in 300+ PHP versions simultaneously
<?php function formatPhone($n) { //Remove any parentheses and the numbers they contain: $n = preg_replace("/\([0-9]+?\)/", "", $n); //Strip spaces and non-numeric characters: $n = preg_replace("/[^0-9]/", "", $n); //Strip out leading zeros: $n = ltrim($n, '0'); //Strip out leading +: $n = ltrim($n, '+'); if(strlen($n) <= 10) { if(substr( $n, 0, 2 ) === "39") return preg_replace('/^39/','+3939', $n); else return '+39' . $n; } else if(strlen($n) > 10){ return preg_replace('/^(?:\+?39|0)?/','+39', $n); }else return '+39' . $n; } echo formatPhone("335123456") . "\n"; echo formatPhone("39335123456") . "\n"; echo formatPhone("+39335123456") . "\n"; echo formatPhone("0039335123456") . "\n"; echo formatPhone("039335123456") . "\n"; echo formatPhone("3931234567") . "\n"; echo formatPhone("+39335123456") . "\n"; echo formatPhone("399123456") . "\n"; echo formatPhone("39399123456") . "\n"; echo formatPhone("+39399123456");
based on STgkf
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.22, 7.4.0 - 7.4.10, 8.0.0alpha1 - beta3
+39335123456 +39335123456 +39335123456 +39335123456 +39335123456 +393931234567 +39335123456 +39399123456 +39399123456 +39399123456