Page 1 of 1

how to count capital letters in a string

Posted: Fri Aug 04, 2006 9:19 am
by chrcapi
How can a PHP 4.x script count capital letters in a string? Anyone ever done this? Thanks!

Posted: Fri Aug 04, 2006 9:24 am
by Jenk
this may work (untested):

Code: Select all

$string = 'aAbBcCdDeE';
preg_match('/[A-Z]{1}/', $string, $matches);
$numberOfMatches = count($matches);

Posted: Fri Aug 04, 2006 9:56 am
by chrcapi
Jenk wrote:

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.
Any idea?

Posted: Fri Aug 04, 2006 1:41 pm
by feyd

Posted: Fri Aug 04, 2006 1:51 pm
by Benjamin

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;
?>

Posted: Fri Aug 04, 2006 4:15 pm
by chrcapi
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;
?>
In this script, the output $counter is always 0. I'm trying a cycle generating every possible capital letters (with chr).
In the meantime, any further idea would be welcomed.
Lot of Thanks to Jenk, Feyd and Astions!

Posted: Fri Aug 04, 2006 4:20 pm
by Benjamin
My Bad, This works..

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;

Posted: Fri Aug 04, 2006 4:36 pm
by chrcapi
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;
It works! Thank you Astions.