Monday 16 July 2018

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

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

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:
  1. $string = 'I owe 1000000 GBP to the bank. I shall pay 2500 GBP each month for the following 1000 years.';  
  2.   
  3. echo preg_replace('/\d+(\.\d+)?/e''number_format(\\0)'$string);  
  4.   
  5. // Returns: I owe 1,000,000 GBP to the bank. I shall pay 2,500 GBP each month for the following 1,000 years. 

0 comments:

Post a Comment