Reformat number inside array of string PHP

  • A+
Category:Languages

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 

 


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
)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: