How to format numbers using regular expression in php?

Member

by deron , in category: PHP General , 6 months ago

How to format numbers using regular expression in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cortez.connelly , 6 months ago

@deron 

To format numbers using regular expressions in PHP, you can use the preg_replace function. Here is an example of how you can format a number with commas as thousands separators:

1
2
3
4
5
6
$number = 1234567;

// Format number with commas as thousands separators
$formattedNumber = preg_replace("/(d)(?=(d{3})+(?!d))/", "$1,", $number);

echo $formattedNumber; // Output: 1,234,567


In this example, the regular expression pattern (d)(?=(d{3})+(?!d)) matches any digit that is followed by groups of three digits, excluding the last group. The preg_replace function replaces each occurrence of this pattern with the matched digit followed by a comma.


You can modify the regular expression pattern to match different number formats according to your needs.

Member

by orpha , 6 months ago

@deron 

Here are some common examples of number formatting using regular expressions in PHP:

  1. Format decimal numbers with two decimal places:
1
2
3
$number = 1234.567;
$formattedNumber = preg_replace("/(d+)(.?d{0,2})/", "$1.$2", $number);
echo $formattedNumber; // Output: 1234.57


  1. Remove all non-digit characters from a number:
1
2
3
$number = "1,234.567";
$formattedNumber = preg_replace("/[^0-9]/", "", $number);
echo $formattedNumber; // Output: 1234567


  1. Format numbers with leading zeros:
1
2
3
$number = "00123";
$formattedNumber = preg_replace("/^0+/", "", $number);
echo $formattedNumber; // Output: 123


  1. Format currency numbers with a dollar sign and two decimal places:
1
2
3
$number = 1234.567;
$formattedNumber = preg_replace("/(d+)(.?d{0,2})/", "$$$1.$2", $number);
echo $formattedNumber; // Output: $1234.57


These are just a few examples of number formatting using regular expressions in PHP. You can customize the regular expressions to match your desired number format.