Shell Suite
Shell Suite

Reputation: 690

Reformat number inside array of string PHP

I have an array which contains strings like this:

$items = array(
  "Receive 10010 from John",
  "Send 1503000 to Jane",
  "Receive 589 from Andy",
  "Send 3454 to Mary"
);

i want to reformat the number inside this array so it will become like this:

$items = array(
  "Receive 10.010 from John",
  "Send 1.503.000 to Jane",
  "Receive 589 from Andy",
  "Send 3.454 to Mary"
);

if i use number_format function it will look like this with number varibale:

$number = '412223';
number_format($number,0,',','.');
echo $number; //412.223

Upvotes: 10

Views: 1394

Answers (3)

bobble bubble
bobble bubble

Reputation: 18535

If you don't expect decimal numbers, you could also use something like

$items = preg_replace('/\d\K(?=(?:\d{3})+\b)/', ".", $items);

See regex demo at regex101 or php demo at eval.in

Upvotes: 1

azizsagi
azizsagi

Reputation: 276

There you go

Follow the following steps

  1. Run through the loop using foreach
  2. Extract the numbers using preg_match_all('!\d+!', $str, $matches);
  3. Apply number format number_format($matches[0],0,',','.');
  4. update array items

So the whole story is to use preg_match_all('!\d+!', $str, $matches); and extract the string number.

Upvotes: 1

iainn
iainn

Reputation: 17434

You can use preg_replace_callback to match a number inside a string and apply some custom formatting. For a single string, this would look like this:

$string = "Receive 10010 from John";

$formatted = preg_replace_callback( "/[0-9]+/", function ($matches) {
    return number_format($matches[0], 0, ',', '.');
}, $string);

echo $formatted;

Receive 10.010 from John


If you want to apply the same logic to your entire array, you can wrap the above in a call to array_map:

$formatted = array_map(function ($string) {
    return preg_replace_callback( "/[0-9]+/", function ($matches) {
        return number_format($matches[0], 0, ',', '.');
    }, $string);
}, $items);

print_r($formatted);

Array
(
  [0] => Receive 10.010 from John
  [1] => Send 1.503.000 to Jane
  [2] => Receive 589 from Andy
  [3] => Send 3.454 to Mary
)

Upvotes: 6

Related Questions