![](/img/trans.png)
[英]How to replace certain character with a defined character for it in a string using 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, '-'));
<?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.