[英]How can I replace each digit with digit[space]?
I have string with mix characters and numbers, how to search for numbers and replace it with the new format? 我有带混合字符和数字的字符串,如何搜索数字并将其替换为新格式?
Input: 输入:
abc def 123 456
expected output: 预期输出:
abc def 1 2 3 4 5 6
I have tried: 我努力了:
preg_replace('/\D/', '', $c)
But this is not dynamic. 但这不是动态的。
EDIT: 编辑:
I forgot to add, that if the numbers have a leading $
it shouldn't replace the numbers. 我忘了补充,如果数字前面有
$
则不应替换数字。
This should work for you: 这应该为您工作:
So you want to replace digits, means use \\d
( [0-9]
) and not \\D
(which is everything else). 因此,您要替换数字,意味着使用
\\d
( [0-9]
)而不是\\D
(这是其他所有内容)。 Then you want to replace each digit with: X
-> X
. 然后,您需要将每个数字替换为:
X
> X
Put that together to: 将其汇总为:
$c = preg_replace("/(\d)(?!$)/", "$1 ", $c);
I just realize that I need to skip any number starting with $ ($1234).
我只是意识到我需要跳过以$($ 1234)开头的任何数字。 what adjustment should I use in regex?
我应该在正则表达式中使用什么调整?
$c = preg_replace('~\$\d+(*SKIP)(*F)|(\d)(?!$)~', "$1 ", $c);
A primitive but functional way to do this would be: 一种原始但实用的方法是:
<?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;
Also, you could generate your mapping programatically if you so chose. 同样,如果您选择这样做,则可以以编程方式生成映射。
Use preg_replace : 使用preg_replace :
$str = "abc def 123 456";
$result = preg_replace('/(\d)/', ' \1 ', $str);
echo $result;
> "abc def 1 2 3 4 5 6 "
to remove the last space use substr : 删除最后一个空格使用substr :
echo substr($result,0,-1);
> "abc def 1 2 3 4 5 6"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.