繁体   English   中英

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

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


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

用短划线“ - ”替换每个单独的数字。

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

期望的输出:

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

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

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

$str = "John is 28 years old and donated $40.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 $40.39!";
$result = strtr($str, '0123456789', array_fill(0, 10, '-'));

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

PHP代码演示

<?php

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

要么:

<?php

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

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

您也可以使用正常替换执行此操作:

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

以防你想知道。 代码已经过测试并且可以运行。 输出是:

约翰已经 - 岁了,捐了$ - .--!

不需要'模糊'的正则表达式。 你还记得斜线和牙套的位置以及原因吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM