Monnster
Monnster

Reputation: 645

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.

Upvotes: 0

Views: 124

Answers (3)

Rizier123
Rizier123

Reputation: 59701

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

Upvotes: 4

Tiago Mazzarollo
Tiago Mazzarollo

Reputation: 37

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"

Upvotes: 1

Brendan Rollinson
Brendan Rollinson

Reputation: 204

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.

Upvotes: 1

Related Questions