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(substr( $n, 0, 2 ) === "39" && strlen($n) <= 10) { return preg_replace('/^39/','+3939', $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");
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
335123495 +39335123456 +39335123456 +39335123456 +39335123456 +393931234567 +39335123456 +39399123456 +39399123456 +39399123456

preferences:
146.52 ms | 403 KiB | 177 Q