Format a Number Within a String Using PHP preg_replace() Function

I owe 1000000 GBP to the bank. I shall pay 2500 GBP each month for the following 1000 years.

The above statement is luckily not true, however it is a good representation of a scenario where we have numbers contained within a string that we wish to format.

The Solution

We could do a complex loop through the string, detecting each of the numbers and formatting them each as we come across them. However with the PHP preg_replace() function we can do this in one quick and easy line of code.

Allow me to demonstrate:

$string = 'I owe 1000000 GBP to the bank. I shall pay 2500 GBP each month for the following 1000 years.';
echo preg_replace('/\d+(\.\d+)?/e', 'number_format(\\0)', $string);
// Returns: I owe 1,000,000 GBP to the bank. I shall pay 2,500 GBP each month for the following 1,000 years.