-1

I have a php string $comment sometimes the $comment box will contain some non alphanumeric characters, is there a way to find out what percentage of $comment is alphanumeric?

Thanks

John
  • 6,417
  • 9
  • 27
  • 32

2 Answers2

4
$comment_alpha = preg_replace('/[^a-z\d]+/i', '', $comment);
$alpha_percent = 100 * strlen($comment_alpha) / strlen($comment);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I'm curious: which of the two steps in this simple procedure were you having trouble doing yourself? – Barmar Feb 12 '14 at 22:10
0

You could try something like this: (Not particularly efficient)

<?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 . "%";

?>

But Regex might be a simpler approach simpler

George
  • 280
  • 3
  • 10