Created
February 26, 2013 14:55
-
-
Save dodopok/5038994 to your computer and use it in GitHub Desktop.
Formatar Strings PHP para qualquer formato
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function __format($campo='',$mascara=''){ | |
//remove qualquer formatação que ainda exista | |
$sLimpo = preg_replace("(/[' '-./ t]/)",'',$campo); | |
// pega o tamanho da string e da mascara | |
$tCampo = strlen($sLimpo); | |
$tMask = strlen($mascara); | |
if ( $tCampo > $tMask ) { | |
$tMaior = $tCampo; | |
} else { | |
$tMaior = $tMask; | |
} | |
//contar o numero de cerquilhas da mascara | |
$aMask = str_split($mascara); | |
$z=0; | |
$flag=FALSE; | |
foreach ( $aMask as $letra ){ | |
if ($letra == '#'){ | |
$z++; | |
} | |
} | |
if ( $z > $tCampo ) { | |
//o campo é menor que esperado | |
$flag=TRUE; | |
} | |
//cria uma variável grande o suficiente para conter os dados | |
$sRetorno = ''; | |
$sRetorno = str_pad($sRetorno, $tCampo+$tMask, " ",STR_PAD_LEFT); | |
//pega o tamanho da string de retorno | |
$tRetorno = strlen($sRetorno); | |
//se houve entrada de dados | |
if( $sLimpo != '' && $mascara !='' ) { | |
//inicia com a posição do ultimo digito da mascara | |
$x = $tMask; | |
$y = $tCampo; | |
$cI = 0; | |
for ( $i = $tMaior-1; $i >= 0; $i-- ) { | |
if ($cI < $z){ | |
// e o digito da mascara é # trocar pelo digito do campo | |
// se o inicio da string da mascara for atingido antes de terminar | |
// o campo considerar # | |
if ( $x > 0 ) { | |
$digMask = $mascara[--$x]; | |
} else { | |
$digMask = '#'; | |
} | |
//se o fim do campo for atingido antes do fim da mascara | |
//verificar se é ( se não for não use | |
if ( $digMask=='#' ) { | |
$cI++; | |
if ( $y > 0 ) { | |
$sRetorno[--$tRetorno] = $sLimpo[--$y]; | |
} else { | |
//$sRetorno[--$tRetorno] = ''; | |
} | |
} else { | |
if ( $y > 0 ) { | |
$sRetorno[--$tRetorno] = $mascara[$x]; | |
} else { | |
if ($mascara[$x] =='('){ | |
$sRetorno[--$tRetorno] = $mascara[$x]; | |
} | |
} | |
$i++; | |
} | |
} | |
} | |
if (!$flag){ | |
if ($mascara[0]!='#'){ | |
$sRetorno = '(' . trim($sRetorno); | |
} | |
} | |
return trim($sRetorno); | |
} else { | |
return ''; | |
} | |
} | |
$string = '35101158716523000119550010000000011003000000'; | |
$string = __format($string, '####-####-####-####-####-####-####-####-####-####-####'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment