have how to put masks in php dynamically?

10

I would like to put masks in different fields, all via php, for example:

cnpj - "##. ###. ### / #### - ##"

cpf - "###. ###. ### - ##"

cep - "##### - ###"

phone - "(##) #### - ####"

date - "## / ## / ####"

I do not want to use jquery, nor masks in javascript, I would like to do it in php itself, because I want to use these masks to format data coming from the database.

    
asked by anonymous 17.07.2014 / 13:35

2 answers

19

php function that puts format fields by putting masks.

function Mask($mask,$str){

    $str = str_replace(" ","",$str);

    for($i=0;$i<strlen($str);$i++){
        $mask[strpos($mask,"#")] = $str[$i];
    }

    return $mask;

}

------------------------ function call -------------------- --------

$cnpj = '17804682000198';
echo Mask("##.###.###/####-##",$cnpj).'<BR>';

$cpf = '21450479480';
echo Mask("###.###.###-##",$cpf).'<BR>';

$cep = '36970000';
echo Mask("#####-###",$cep).'<BR>';

$telefone = '3391922727';
echo Mask("(##)####-####",$telefone).'<BR>';

$data = '21072014';
echo Mask("##/##/####",$data);
    
17.07.2014 / 13:35
15

You can use vsprintf as follows:

function format($mask,$string)
{
    return  vsprintf($mask, str_split($string));
}

Example:

$cnpjMask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s";
echo format($cnpjMask,'11622112000109');
11.622.112/0001-09
    
13.11.2014 / 20:50