Php 如何计算匹配字符的数量?

Php 如何计算匹配字符的数量?,php,regex,Php,Regex,我想用零来代替一系列的数字。始终希望保留第一个数字,并用零替换所有其他数字。大概是这样的: $numb = 4124; $newnumb = 4000; // what I want 注意:有时会有这样的浮点数212.1。对于浮点数,我与浮点数部分不匹配。所以在212.1中,我只匹配212 这是我的模式: ^(\d)([^\.]+) 现在,$1包含第一个数字,我想知道如何将0替换为其余数字 示例: 423.13 => 400 1232 => 1000 99.12

我想用零来代替一系列的数字。始终希望保留第一个数字,并用零替换所有其他数字。大概是这样的:

$numb    = 4124;
$newnumb = 4000;  // what I want

注意:有时会有这样的浮点数
212.1
。对于浮点数,我与浮点数部分不匹配。所以在
212.1
中,我只匹配
212


这是我的模式:

^(\d)([^\.]+)
现在,
$1
包含第一个数字,我想知道如何将
0
替换为其余数字


示例:

423.13 => 400
1232   => 1000
99.123 => 90


我如何使用正则表达式来实现这一点

由于您已经有了完善的正则表达式
^(\d)([^\.]+)
,您只需使用
preg\u replace\u callback()
,并使用第二个捕获组中的字符量作为要使用
str\u repeat()
打印的0量,例如

echo preg_replace_callback("/^(\d)([^\.]+)\..*/", function($m){
    return $m[1] . str_repeat(0, strlen($m[2]));
}, $string);

由于您已经有了完整的正则表达式
^(\d)([^\.]+)
,您只需要使用
preg\u replace\u callback()
,并使用第二个捕获组中的字符量作为您要使用
str\u repeat()
打印的0的数量,例如

echo preg_replace_callback("/^(\d)([^\.]+)\..*/", function($m){
    return $m[1] . str_repeat(0, strlen($m[2]));
}, $string);

您可以使用
\G
锚定:

echo preg_replace('/(?:\G(?!\A)|\d)\K\d(?:\.\d*)?/S', '0', $num);
详情:

(?:
    \G        # position after the previous match 
    (?!\A)    # (but not at the start of the string)
  |           # OR
    \d        # first digit (you can also check if there is no leading dot)
)
\K            # start the match result at this position
              # (to preserve the first digit)
\d
(?:\.\d*)? # eventual decimals (you can change * to + to avoid to
           # remove a dot that ends a sentence)
更有效的方法(在开始时使用系数中的
\d
):


echo preg\u replace('/\d(?:(?您可以使用
\G
锚定:

echo preg_replace('/(?:\G(?!\A)|\d)\K\d(?:\.\d*)?/S', '0', $num);
详情:

(?:
    \G        # position after the previous match 
    (?!\A)    # (but not at the start of the string)
  |           # OR
    \d        # first digit (you can also check if there is no leading dot)
)
\K            # start the match result at this position
              # (to preserve the first digit)
\d
(?:\.\d*)? # eventual decimals (you can change * to + to avoid to
           # remove a dot that ends a sentence)
更有效的方法(在开始时使用系数中的
\d
):


echo preg\u replace('/\d(?((
$numb
,这是一个新的…
$numb
,这是一个新的…
@stack如果要删除浮动部分,只需将
\..*
添加到堆栈的末尾即可RegEx@stack浮动部分仍然在那里,我看错了你的问题。如果你想删除它,就像Druzion说的那样,只需使用
\..*
匹配点和它后面的所有内容。(将更新答案)@堆栈如果要删除浮动部分,只需将
\..*
添加到RegEx@stack浮动部分仍然在那里,我看错了你的问题。如果你想删除它,就像Druzion说的那样,只需使用
\..*
匹配点和它后面的所有内容。(将更新答案)我认为你是能使用
\G
锚的最佳人选。因为这是我从你那里得到的第二个答案()。再次感谢你。我认为你是能使用
\G
锚的最佳人选。因为这是我从你那里得到的第二个答案()。再次感谢你