Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Php format string with pattern

I have a string (trimmed) and I would like to split this string according to a predefined pattern. I wrote a code which is probably more interpretive.

    $string="123456789";
    $format=['XXX','XX','XXXX'];
    $formatted="";
    foreach ($format as $cluster){
        $formattedCluster=substr($string,0,strlen($cluster));
        $string=substr($string,strlen($cluster));
        $formatted.=$formattedCluster.' ';
    }
    $formatted=substr($formatted, 0, -1);

    dd($formatted);

    //outputs: "123 45 6789"

As you can see it takes a string without any whitespace, and separates it with whitespaces according to a pattern $format in this case. The pattern is an array.

A pseudo example:

$str='qweasdzxc'

$pattern=['X','X','XXXX','XXX']

$formatted='q w easd zxc'; //expected output

It works as expected but it is rather hideous. What is the correct solution to this problem? By correctness, I mean speed and readability.

Environment: Php 7.4, Laravel 8

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I would use https://www.php.net/manual/en/function.vsprintf.php do get the result:

$str='qweasdzxc';
$pattern='% % %%%% %%%'; // ['X','X','XXXX','XXX']
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));
over 4 years ago · Santiago Trujillo Relatório

0

$string = "qweasdzxc";
$chunks = array(1,1,4,3);
// Optional check to ensure that $string can be divided into requested chunks
if(array_sum($chunks) <> strlen($string)) { 
    echo "String length does not fit requested chunks.";
}
$i=0;
$output = "";
foreach($chunks as $chunk) { 
    $output .= substr($string,$i,$chunk) . " ";
    $i += $chunk;
}

echo rtrim($output);
// Outputs "q w easd zxc"

Probably an easier way to remove the whitespace from the right hand end by not adding it in the first place based on whether or not it's the last element of the array, but that does the trick.

over 4 years ago · Santiago Trujillo Relatório

0

easy way to use preg_match try this.

$data = '11234567890';

if(preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches))
{
    $result = $matches[1] . ' ' .$matches[2] . ' ' . $matches[3];
    echo  $result;
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda