简体   繁体   English

如何计算匹配的字符数?

[英]How to count the number of matched characters?

I'm trying to replace a sequence of numbers with zero. 我正在尝试将数字序列替换为零。 Always want to keep first digit and replace all the rest with zero. 始终希望保留第一位数字,并将其余所有数字替换为零。 Something like this: 像这样:

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

Note: Sometimes there is a float number like this 212.1 . 注意:有时会有一个像212.1这样的浮点数。 For float numbers I don't match float part. 对于浮点数,我不匹配浮点数部分。 So in 212.1 , I just match 212 . 所以在212.1 ,我只匹配212


Here is my pattern: 这是我的模式:

^(\d)([^\.]+)

Now $1 contains first digit, and I want to know how can I put 0 instead of the rest of the digits? 现在$1包含第一个数字,我想知道如何放置0而不是其余数字?


Examples: 例子:

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

How can I do that using regex? 我该如何使用正则表达式呢?

As you already have the prefect regex ^(\\d)([^\\.]+) you just need to use preg_replace_callback() and use the amount of characters in the second capturing group for the amount of 0's you want to print with str_repeat() , eg 由于您已经拥有完善的正则表达式^(\\d)([^\\.]+) ,因此只需要使用preg_replace_callback()并将第二个捕获组中的字符数用于要使用str_repeat()打印的0数str_repeat() ,例如

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

You can use the \\G anchor: 您可以使用\\G锚点:

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

details: 细节:

(?:
    \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)

More efficient way (with \\d in factor at the beginning) : 更有效的方法(在开头加上\\d

echo preg_replace('/\d(?:(?<=\G.)|\K\d)(?:\.\d+)?/', '0', $num);

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

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