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

435
Visualizações
Python-like .format() in php

I have the following array:

$matches[0] = "123";
$matches[1] = "987";
$matches[2] = "121";

And the following string:

$result = "My phone number is {0} and police number is {2}";

I would like to replace the {} placeholder based on the $matches array, in case there is no match for placeholder display nothing instead.

What is the best way to achieve that, or do you know a better solution to my problem?

(Right now I am building the system, so instead of curly brackets I could use any other symbol)

UPDATE

In python this is possible using .format() function.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can do it with vsprintf, you don't have to change the order of items if you give the number (from 1) of your item like this: %n$s (where n is the number):

$matches = [ "123", "987", "121"];
$result = 'My phone number is %1$s and police number is %3$s';

$res = vsprintf($result, $matches);

Note that you have to put the formatted string between single quotes, otherwise $s will be interpreted as a variable and replaced with nothing.

(vprintf and vsprintf are designed for arrays, but you can do the same thing with printf and sprintf for separated variables, it works the same)


If you can't change your original Python formatted string, the way is to use preg_replace_callback:

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$res = preg_replace_callback('~{(\d+)}~', function ($m) use ($matches) {
    return isset($matches[$m[1]]) ? $matches[$m[1]] : $m[0];
}, $result);

or you can build an associative array where the keys are placeholders and values your array values, and use strtr for the replacement:

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$trans = array_combine(
    array_map(function ($i) { return '{'.$i.'}'; }, array_keys($matches)),
    $matches
);

$result = strtr($result, $trans);
about 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