Home > Software design >  How to format numbers using Regular Expression in PHP
How to format numbers using Regular Expression in PHP

Time:10-05

I would need to change the format to 123.456.789.11, so far I have only managed to do it as shown in the example https://regex101.com/r/sY1nH4/1, but I would need it to always have 3 digits at the beginning, thank you for your help

$repl = preg_replace('/(?!^)(?=(?:\d{3}) $)/m', '.', $input);

CodePudding user response:

You should assert that it is not the end of the string instead to prevent adding a dot at the end:

\d{3}(?!$)\K
  • \d{3} Match 3 digits
  • (?!$) Negative lookahead, assert not the end of the string to the right
  • \K Forget what is matched so far

Regex demo

$re = '/\d{3}(?!$)\K/m';
$str = '111222333444
11222333444';

$result = preg_replace($re, ".", $str);

echo $result;

Output

111.222.333.444
112.223.334.44

CodePudding user response:

I would use this approach, using a capture group:

$input = "12345678911";
$output = preg_replace("/(\d{3})(?=\d)/", "$1.", $input);
echo $output;  // 123.456.789.11

The above replaces every 3 numbers, starting from the left, with the same numbers followed by a dot, provided that at least one other digit follows.

CodePudding user response:

Here is a possible solution using \B (opposite of \b):

\d{3}\B\K

Replace it with .

RegEx Demo

By using \B after 3 digits we ensure that we don't match the last position.

CodePudding user response:

No need for a regular expression actually. split into equal parts, join with comma:

$formatted = implode(',', str_split($str, 3));
  • Related