[英]How to count the number of matched characters?
我正在嘗試將數字序列替換為零。 始終希望保留第一位數字,並將其余所有數字替換為零。 像這樣:
$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_replace_callback()
並將第二個捕獲組中的字符數用於要使用str_repeat()
打印的0數str_repeat()
,例如
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_replace('/\d(?:(?<=\G.)|\K\d)(?:\.\d+)?/', '0', $num);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.