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.
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
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 $--.--!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With