![](/img/trans.png)
[英]How can I replace every second digit to another digit using if else statement in php?
[英]How can I replace each digit with digit[space]?
我有帶混合字符和數字的字符串,如何搜索數字並將其替換為新格式?
輸入:
abc def 123 456
預期輸出:
abc def 1 2 3 4 5 6
我努力了:
preg_replace('/\D/', '', $c)
但這不是動態的。
編輯:
我忘了補充,如果數字前面有$
則不應替換數字。
一種原始但實用的方法是:
<?php
$input = 'abc def 123 456';
$mapping = [
'1' => '1 ',
'2' => '2 ',
'3' => '3 ',
'4' => '4 ',
'5' => '5 ',
'6' => '6 ',
'7' => '7 ',
'8' => '8 ',
'9' => '9 ',
'0' => '0 ',
];
foreach ($mapping as $before => $after) {
$input = str_replace($before, $after, $input);
}
echo $input;
同樣,如果您選擇這樣做,則可以以編程方式生成映射。
使用preg_replace :
$str = "abc def 123 456";
$result = preg_replace('/(\d)/', ' \1 ', $str);
echo $result;
> "abc def 1 2 3 4 5 6 "
刪除最后一個空格使用substr :
echo substr($result,0,-1);
> "abc def 1 2 3 4 5 6"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.