[英]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.