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

366
Visualizações
How do you replace all numbers in a string with a defined character in PHP?

How would you replace all numbers in a string with a pre-defined character?

Replace each individual number with a dash "-".

$str = "John is 28 years old and donated $40.39!";

Desired output:

"John is -- years old and donated $--.--!"

I am assuming preg_replace() will be used but I am not sure how to target just numbers.

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

0

Simple solution using strtr(to translate all digits) and str_repeat functions:

$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', str_repeat('-', 10));

print_r($result);

The output:

John is -- years old and donated $--.--!

As alternative approach you may also use array_fill function(to create "replace_pairs"):

$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', array_fill(0, 10, '-'));

http://php.net/manual/en/function.strtr.php

about 4 years ago · Santiago Trujillo Relatório

0

PHP code demo

<?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/\d/", "-", $str);

OR:

<?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/[0-9]/", "-", $str);

Output: John is -- years old and donated $--.--!

about 4 years ago · Santiago Trujillo Relatório

0

You can also do this with a normal replace:

$input   = "John is 28 years old and donated $40.39!";
$numbers = str_split('1234567890');
$output  = str_replace($numbers,'-',$input);
echo $output;

just in case you were wondering. Code was tested and it works. The output is:

John is -- years old and donated $--.--!

No need for 'obscure' regular expressions. Do you remember where the slashes and braces go and why?

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