Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers using Regular Expression in PHP

Tags:

regex

php

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);
like image 831
Tomas Avatar asked May 24 '26 09:05

Tomas


2 Answers

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
like image 55
The fourth bird Avatar answered May 26 '26 00:05

The fourth bird


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.

like image 45
Tim Biegeleisen Avatar answered May 26 '26 00:05

Tim Biegeleisen