How do you replace all numbers in a string with a specific character in PHP?


How would you replace all numbers in a string with a predefined character?

Replace each individual number with a dash "-".

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

      

Desired output:

$str = "John is -- years old and donated $--.--!";

      

I guess it preg_replace()

will be used, but I'm not sure how to target the numbers only.

+3


source to share


3 answers


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);

      

Output:

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

      




Alternatively, you can also use array_fill (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

+4


source


PHP 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 $--.--!

+2


source


You can also do it with a normal replacement:

$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're wondering. The code has been tested and it works. Output:

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

No need for "obscure" regular expressions. Do you remember where the slash and curly braces go and why?

+1


source







All Articles