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
)
There you go
Follow the following steps
So the whole story is to use preg_match_all('!\d+!', $str, $matches); and extract the string number.
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(?=(?:\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With