简体   繁体   中英

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). Then you want to replace each digit with: 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). what adjustment should I use in regex?

$c = preg_replace('~\$\d+(*SKIP)(*F)|(\d)(?!$)~', "$1 ", $c);

DEMO

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 :

$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 :

echo substr($result,0,-1);
> "abc def  1  2  3   4  5  6"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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