5
I have two ways to create masks for numbers in PHP, but I don’t know if it’s the most elegant and effective, so I would like to have some options 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 (can be a hyphen) in the middle of these 8 numbers. That is,
11112222
will transform into1111-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);
Someone knows a better way, in terms of performance and elegance, without having to call multiple functions to create a PHP mask?
who is this guy
chunk_split
!? I don’t remember him– Wallace Maxters
Ooooh! That’s cool! Very cool, this one
chunk_split
!– Wallace Maxters
I think I’m gonna adopt the
str_pad
also. Every time I have to stay using thesprintf
with that ugly concatenation"0{$size}s%"
.– Wallace Maxters
In case you should not have specified in str_pad the pad_type as STR_PAD_LEFT? By default it will be filled to the right of the value.
– Marcelo de Andrade
@Marcelodeandrade well remembered, I changed the code and the explanation of the answer xD
– rray