Jump to content

Archived

This topic is now archived and is closed to further replies.

Brandon Jaeger

Upper-case char. count

Recommended Posts

How would I get the number of upper-case characters in a string and make a percentage out of it (out of 100%)?

Thanks in advance.

---brandon

Share this post


Link to post
Share on other sites
Might look at the 8th comment here...

[a href=\"http://us3.php.net/strtoupper\" target=\"_blank\"]http://us3.php.net/strtoupper[/a]

Lite...

Share this post


Link to post
Share on other sites
Thanks!

I had to make some minor changes to his function:
[code]    function get_upper_percent($str)
    {
        $len   = 0;
        $upper = 0;

        $strlen = strlen($str);

        for($i = 0; $i <= $strlen; ++$i)
        {
            if($str[$i] <> strtolower($str[$i]))
            {
                ++$len;
                ++$upper;
            }

            if($str[$i] <> strtoupper($str[$i]))
                ++$len;
        }
            
        $percent = 0;

        if($len > 0)
            $percent = ($upper/$len) * 100;
            
        return substr($percent , 0 , (($percent > 99) ? 3 : 2));
    }[/code]
Although it's not correct all of the time.

The string "aaaAAA" comes out as 60% caps with that function.

Any help?

Edit: SOLVED!

Share this post


Link to post
Share on other sites
Use this function to do most of the work for you:
[a href=\"http://www.php.net/manual/en/function.count-chars.php\" target=\"_blank\"]http://www.php.net/manual/en/function.count-chars.php[/a]

Then you can use the array_slice() function:
[a href=\"http://www.php.net/manual/en/function.array-slice.php\" target=\"_blank\"]http://www.php.net/manual/en/function.array-slice.php[/a]
[code]$capitalletters = array_slice($charcountarray, ord('A'), 26);[/code]
then you can use this function:
[a href=\"http://www.php.net/manual/en/function.array-sum.php\" target=\"_blank\"]http://www.php.net/manual/en/function.array-sum.php[/a]
[code]$totalcaplets = array_sum($capitalletters);[/code]
--Use a similiar method to get the sum of the small letters. It is not the sum of the count_chars function, that will count punctuation, tabs, line feeds, spaces, and any control characters as well.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.