how to count capital letters in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
chrcapi
Forum Newbie
Posts: 4
Joined: Fri Aug 04, 2006 9:16 am

how to count capital letters in a string

Post by chrcapi »

How can a PHP 4.x script count capital letters in a string? Anyone ever done this? Thanks!
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

this may work (untested):

Code: Select all

$string = 'aAbBcCdDeE';
preg_match('/[A-Z]{1}/', $string, $matches);
$numberOfMatches = count($matches);
chrcapi
Forum Newbie
Posts: 4
Joined: Fri Aug 04, 2006 9:16 am

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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;
?>
chrcapi
Forum Newbie
Posts: 4
Joined: Fri Aug 04, 2006 9:16 am

Post 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!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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;
chrcapi
Forum Newbie
Posts: 4
Joined: Fri Aug 04, 2006 9:16 am

Post 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.
Post Reply