[英]Count number of character occurrences in a string in PHP without use available function
[英]Function to count number of digits in string
我正在尋找一個快速的PHP函數,給定一個字符串,將計算該字符串中的數字字符(即數字)的數量。 我找不到一個,有沒有這樣做的功能?
這可以通過正則表達式輕松完成。
function countDigits( $str )
{
return preg_match_all( "/[0-9]/", $str );
}
該函數將返回找到模式的次數,在本例中為任何數字。
首先拆分你的字符串 ,然后過濾結果只包含數字字符,然后簡單地計算結果元素。
<?php
$text="12aap33";
print count(array_filter(str_split($text),'is_numeric'));
編輯:出於好奇心添加了一個基准:(上述字符串和例程的1000000循環)
preg_based.php是overv的preg_match_all解決方案
harald@Midians_Gate:~$ time php filter_based.php
real 0m20.147s
user 0m15.545s
sys 0m3.956s
harald@Midians_Gate:~$ time php preg_based.php
real 0m9.832s
user 0m8.313s
sys 0m1.224s
正則表達明顯優越。 :)
對於PHP <5.4:
function countDigits( $str )
{
return count(preg_grep('~^[0-9]$~', str_split($str)));
}
此函數遍歷給定的字符串並檢查每個字符以查看它是否為數字。 如果是,則遞增數字位數,然后在結尾處返回。
function countDigits($str) {
$noDigits=0;
for ($i=0;$i<strlen($str);$i++) {
if (is_numeric($str{$i})) $noDigits++;
}
return $noDigits;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.