简体   繁体   English

如何在 PHP 中使用正则表达式格式化数字

[英]How to format numbers using Regular Expression in 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我需要将格式更改为123.456.789.11 ,到目前为止,我只能按照示例https://regex101.com/r/sY1nH4/1中所示进行操作,但我需要它始终具有 3 位数字一开始,谢谢你的帮助

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

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 \d{3}匹配3个数字
  • (?!$) Negative lookahead, assert not the end of the string to the right (?!$)否定前瞻,断言不是字符串的结尾到右边
  • \K Forget what is matched so far \K忘记到目前为止匹配的内容

Regex demo正则表达式演示

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

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

echo $result;

Output Output

111.222.333.444
112.223.334.44

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.上面的代码从左边开始每 3 个数字替换为相同的数字后跟一个点,前提是至少要跟一个其他数字。

Here is a possible solution using \B (opposite of \b ):这是使用\B (与\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.通过在 3 位数字后使用\B ,我们确保不匹配最后的 position。

No need for a regular expression actually.实际上不需要正则表达式。 split into equal parts, join with comma:分成相等的部分,用逗号连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM