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

September 14th, 2012 - Posted by Steve Marks to PHP, Web Development.

Let’s imagine we have the following string:

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.
This entry was posted on Friday, September 14th, 2012 at 12:11 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first