Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 314
Shell Suite Avatar asked Jul 23 '18 10:07

Shell Suite


3 Answers

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
)

like image 198
iainn Avatar answered Oct 18 '22 00:10

iainn


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.

like image 1
azizsagi Avatar answered Oct 17 '22 22:10

azizsagi


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

$items = preg_replace('/\d\K(?=(?:\d{3})+\b)/', ".", $items);
  • \d is a shorthand for digit [0-9]
  • \K resets beginning of the reported match
  • after every digit the lookahead (?=(?:\d{3})+\b) checks if there are multiples of three digits ahead until the next word boundary (end of the number).

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

like image 1
bobble bubble Avatar answered Oct 17 '22 22:10

bobble bubble