What is the simplest way to create a mask for numbers in PHP?

5

I have two ways to create masks for numbers in PHP, however I do not know if it is the most elegant and effective, so I would like comments to improve the code.

I need the function to behave as follows:

  • Format numbers with less than 8 numbers by filling them with zero .
  • Create a separator (it can be a hyphen) in the middle of these 8 numbers. That is, 11112222 will transform to 1111-2222 .

I already have these two examples:

Example 1:

implode('-', str_split(sprintf('%08s', $numero), 4));

Example 2

$formatado = sprintf('%08s', $numero);

substr($formatado, 0, 4) . '-' . substr($formatado, 4, 8);

Does anyone know a better way, in terms of performance and elegance, without having to call various functions to create a mask in PHP?

    
asked by anonymous 26.08.2015 / 17:24

3 answers

8

One way to work around this is to combine str_pad () to fill in the leading zeros * if the string is less than 8 characters, chunk_split () to insert the hyphen every 4 characters and the trim () to remove the added hyphen at the end.

<?php

function mascaraTelefone($numero){
    $numero = str_pad($numero, 8, '0', STR_PAD_LEFT);
    return trim(chunk_split($numero, 4, '-'), '-');
}

echo mascaraTelefone('9999') .PHP_EOL;
echo mascaraTelefone('99998888') .PHP_EOL;
echo mascaraTelefone('77') .PHP_EOL;
echo mascaraTelefone('666') .PHP_EOL;

Example - ideone

Based on: 5-character dot insertion

A variant of this code is to change chunck_split() to substr_replace () which replaces a copy of the character that is in position X (third argument) by hyphen in the case.

function mascaraTelefone($numero){
    $numero = str_pad($numero, 8, '0', STR_PAD_LEFT);
    return substr_replace($numero, '-', 4, 0);
}

* The default behavior of str_pad() is to add the characters to the right, this can be modified by entering the fourth argument of the function which has the following values:

STR_PAD_RIGHT|Adiciona a direita(padrão caso o quarto argumento seja omitido
STR_PAD_LEFT |Adiciona a esquerda
STR_PAD_BOTH |Adiciona na esquerda e na direita
    
26.08.2015 / 17:36
6

Generic formatting with dynamic mask:

function format_string($mask, $str, $ch = '#') {
    $c = 0;
    $rs = '';

    /*
    Aqui usamos strlen() pois não há preocupação com o charset da máscara.
    */
    for ($i = 0; $i < strlen($mask); $i++) {
        if ($mask[$i] == $ch) {
            $rs .= $str[$c];
            $c++;
        } else {
            $rs .= $mask[$i];
        }
    }

    return $rs;
}

$str = '05055344410'; // Exemplo para telefone
echo format_string('###-####-####', $str);
$str = '20150827'; // Exemplo para datas
echo '<br />' . format_string('####-##-##', $str);
    
26.08.2015 / 17:45
1

It is very well answered, but I would like to leave here a little technique that uses vsprintf and str_split together.

The vsprintf function is intended to format a string, based on the arguments passed. But other than sprintf , instead of passing n parameters, you pass array . So, we could use the str_split function to separate the strings and, with vsprintf , apply the formatting.

In this example, I passed a second argument to str_split , which will cause the string to be divided by 4, as is the case with the phones.

function formatar_telefone($telefone) {
     return vsprintf('%s-%s', str_split($telefone, 4));
}

Of course there will be problems if the phone number does not contain 8 digits. So in this case, it may be to add a check inside the function, with a posting of an error or exception. Or just fill in the values with 0 , as the @rray suggested.

In this case, we could fill in using sprintf to fill with zeros, using the expression %08d :

function formatar_telefone($telefone) {
     vsprintf('%s-%s%', str_split(sprintf('%08d', $telefone)));
}

The expression %08d means that you want to format a number, forcing it to be recognized as a digit, and if it is less than 8 characters, it will be filled with 0 .

    
05.08.2016 / 14:06