Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sometimes, we need to know how many of each character is in a string. This PHP code does just that.
<?
function getLetterCount($input) {
$letters = array();
//make lowercase to simplify counting
$temp = strtolower(trim($input));
//get length of string
$templen = strlen($temp);
//get each character in string
for($i = 0; $i < $templen; $i++) {
$char = substr($temp, $i, 1);
//if it's a letter, increment its counter in array
if(eregi('[a-z]', $char)) {
$letters[$char] += 1;
}
}
//sort array by key name
ksort($letters);
//return array
return $letters;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
Count Letters In A String With PHP
Copyright 2007 Doug Vanderweide, dba Rescue-ME
http://www.dougv.com
Distributed under the Creative Commons Attribution / Share-Alike 2.5 License
http://creativecommons.org/licenses/by-sa/2.5/
Any distribution or derivative work based on this script must include the
original source code from this work, and must retain this copyright
notice block intact.
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Count Letters In A String With PHP</title>
<link href="../demo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Count Letters In A String With PHP</h1>
<?
if(isset($_POST['submit'])) {
$countstring = substr($_POST['mystring'], 0, 255);
$output = getLetterCount($countstring);
echo "<h3>The input string was:</h3>\n";
echo $countstring;
echo "<h3>Letter count displayed using foreach:</h3>\n";
foreach($output as $key => $value) {
echo "$key: $value<br />";
}
//output array to screen
echo "<h3>Letter count displayed using print_r:</h3>\n";
print_r($output);
$mystring = $_POST['mystring'];
}
else {
$mystring = "The quick brown fox jumps over the lazy dog.";
}
?>
<p>&nbsp;</p>
<form id="form1" name="form1" method="post" action="">
<label for="textfield">Enter the string:</label>
<input name="mystring" type="text" id="mystring" value="<? echo $mystring; ?>" size="50" maxlength="255" />
<input name="submit" type="submit" id="submit" value="Count Letters" />
</form>
<p><a href="http://www.dougv.com/blog/2007/01/03/counting-letters-in-a-string-with-php/" rel="bookmark" title="Permanent Link to Counting Letters In A String With PHP">Counting Letters In A String With PHP</a></p>
<p>&nbsp;</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.