Is there any way to dynamically put a mask in php?

Asked

Viewed 23,421 times

12

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

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

Cpf - "###.###.###-##"

zip code - "#####-###"

telephone - "(##)####-####"

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

I don’t want to use jquery, or javascript masks, I would like to do it in php anyway, because I want to use these masks to format data coming from the database.

  • 1

    The expression "dynamically" is usually used when we refer to a change in HTML after it is already loaded on the page, so what you want is to mask before the HTML presentation ;)

  • I think "waste" doing this in server-side, will create an unnecessary work, which could be easily transferred to the customer, in your browser, but that’s just my opinion.

2 answers

25

php function that puts format the 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);
  • Functional, clean and readable. Thank you!

  • Excellent! Thank you.

20

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
  • 1

    simple option that uses features already available in php

  • Very simple and works well. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.