how to count capital letters in a string
Posted: Fri Aug 04, 2006 9:19 am
How can a PHP 4.x script count capital letters in a string? Anyone ever done this? Thanks!
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
$string = 'aAbBcCdDeE';
preg_match('/[A-Z]{1}/', $string, $matches);
$numberOfMatches = count($matches);The output is always "1", even with preg_match_all instead of preg_match.Jenk wrote:Code: Select all
$string = 'aAbBcCdDeE'; preg_match('/[A-Z]{1}/', $string, $matches); $numberOfMatches = count($matches);
Code: Select all
<?php
$length = strlen($String);
$counter = 0;
for ($i = 0; $i < $length; $i++)
{
if ((chr($String{$i}) > 64) && (chr($String{$i}) < 91))
{
$counter++;
}
}
echo $counter;
?>In this script, the output $counter is always 0. I'm trying a cycle generating every possible capital letters (with chr).astions wrote: <?php
$length = strlen($String);
$counter = 0;
for ($i = 0; $i < $length; $i++)
{
if ((chr($String{$i}) > 64) && (chr($String{$i}) < 91))
{
$counter++;
}
}
echo $counter;
?>
Code: Select all
$String = "This Is A Capital Letter Test";
$length = strlen($String);
$counter = 0;
for ($i = 0; $i < $length; $i++)
{
if ((ord($String{$i}) > 64) && (ord($String{$i}) < 91))
{
$counter++;
}
}
echo $counter;It works! Thank you Astions.astions wrote:Code: Select all
$String = "This Is A Capital Letter Test"; $length = strlen($String); $counter = 0; for ($i = 0; $i < $length; $i++) { if ((ord($String{$i}) > 64) && (ord($String{$i}) < 91)) { $counter++; } } echo $counter;