如何使用PHP格式化数字到塞尔维亚格式?

如何使用PHP格式化数字到塞尔维亚格式?

问题描述:

I have number sent from form like this:

0641234567
064-123/4567
064/123-4567
3816412345678

And it needs to be like this:

+3816412345678

with +, without 0 and with max 14 characters including '+'.

How can i solve that using regex?

我从这样的表格发送号码: p>

  0641234567  
064-123 / 4567 
064 / 123-4567 
3816412345678 
  code>  pre> 
 
 

它必须是这样的: p>

   +3816412345678 
  code>  pre> 
 
 

+,不带0,最多14个字符,包括'+'。 p>

怎么能 我使用正则表达式来解决这个问题? p> div>

All you need is multiple replacement with basically three rules,

  • replace - or / with empty string
  • replace the zero in the beginning with +381
  • Put a + in the beginning of number if the first number is any 1 to 9

Check this PHP Demo,

$arr = ['0641234567','064-123/4567','064/123-4567','3816412345678'];

foreach($arr as $s) {
    echo $s." --> ".preg_replace(['/^0/', '/^(?=[1-9])/', '/[-\/]/'], ['+381', '+', ''], $s)."
";
}

Prints,

0641234567 --> +381641234567
064-123/4567 --> +381641234567
064/123-4567 --> +381641234567
3816412345678 --> +3816412345678

Let me know if any of your case goes uncovered.

The data you showed may be incomplete, and there could be edge cases other than what we can see right. Based on what we do see right now, your replacement can be implemented by replacing a leading 064 with 38164, and then stripping all dashes and forward slashes. Using preg_replace:

$input = "064-123/4567";
$output = preg_replace('/[\/-]/', '', preg_replace('/^064/', '38164', $input));
echo $input . "
" . $output;

064-123/4567
381641234567