PHP检查字符串是否包含特定百分比的字母数字字符

时间:2014-02-12 21:50:41

标签: php alphanumeric non-alphanumeric

我有一个php字符串$ comment有时$ comment框会包含一些非字母数字字符,有没有办法找出$ comment的百分比是多少?

由于

2 个答案:

答案 0 :(得分:4)

$comment_alpha = preg_replace('/[^a-z\d]+/i', '', $comment);
$alpha_percent = 100 * strlen($comment_alpha) / strlen($comment);

答案 1 :(得分:0)

你可以尝试这样的事情:(效率不高)

<?php
$string = "TestItOut##@22383";



$all = array(
"0","1","2","3","4","5","6","7","8","9",          
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",     
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
);

$num_alphanum = 0;
foreach ( $all as $char ) {
    $num_alphanum += substr_count( $string, $char );
}

$percent = ( $num_alphanum / strlen( $string ) ) * 100;

echo $percent . "%";

?>

但是Regex可能是一种更简单的方法