如何用 PHP 中定义的字符替换字符串中的所有数字?

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


如何用预定义字符替换字符串中的所有数字?

用破折号“-”替换每个单独的数字。

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

期望的输出:

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

我假设 preg_replace() 将被使用,但我不确定如何仅针对数字。

PHP code demo

<?php

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

或:

<?php

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

输出: John is -- years old and donated $--.--!

您也可以使用普通替换来执行此操作:

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

以防万一你想知道。代码已经过测试并且可以正常工作。输出为:

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

不需要 'obscure' 正则表达式。你还记得斜杠和大括号的去向吗?为什么?

使用strtr(翻译所有数字)和str_repeat函数的简单解决方案:

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

print_r($result);

输出:

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

作为替代方法,您还可以使用 array_fill 函数(创建 "replace_pairs"):

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

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