-1

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

谢谢

4

2 回答 2

4
$comment_alpha = preg_replace('/[^a-z\d]+/i', '', $comment);
$alpha_percent = 100 * strlen($comment_alpha) / strlen($comment);
于 2014-02-12T21:53:32.887 回答
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 . "%";

?>

但是正则表达式可能是一种更简单的方法

于 2014-02-12T22:04:44.490 回答