Jump to content

Archived

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

CanMan2004

counting numbers \ letters

Recommended Posts

Dear all

Is there a way to count the number of numbers in a value and the number of letters in a value? I know you can count the total number of letters and numbers, what im looking for is something that if I had the value

HE11O22

then it would count the numbers as 4 (1122) and the letters as 3 (HEO)

Is this possible?

Thanks in advance

Ed

Share this post


Link to post
Share on other sites
There are meny ways to do this, You can brake the code down in an array and count with strlen or you could use eregi and count with strlen even other ways.

good luck.

Share this post


Link to post
Share on other sites
There are several ways you can go about this, I've picked this method at random:
[code]<?php
$string = strtolower("HE11O22");
$letters = 0;
$numbers = 0;

for($i=0; $i<strlen($string); $i++) {
    if(in_array($string{$i},range("a","z"))) $letters++;
    elseif(in_array($string{$i},range("0","9"))) $numbers++;
}
echo "Letters: $letters<br/>Numbers: $numbers";
?>[/code]

Share this post


Link to post
Share on other sites
Easiest/quickest way:

[code]<?php

$string = 'HE11O22';

$numAlpha = strlen(preg_replace('/[^a-z]+?/i', '', $string));
$numNumerical = strlen(preg_replace('/[^0-9]+?/i', '', $string));

?>[/code]

Share this post


Link to post
Share on other sites
Hi

Thanks for all the help, following this, if I had the following value

45 ROADE

Is there a way for php to tell if the 2nd word (ROADE) starts with a number or a letter and then flag up yes or no if it does.

For example, it would return "yes" if the value was

45 4ROADE

and it would return "no" if the value was

45 ROADE

Not sure if this is possible though, although, you guys seem to be able to resolve most questions.

Thanks in advance for any further help

Cheers

Ed

Share this post


Link to post
Share on other sites
For your specific example (and for similarly formatted examples), this should work:
[code]<?php
$str = "45 ROADE";
$tmp = explode(" ",$str);
echo (is_numeric($tmp[1]{0})) ? "Yes" : "No";
?>[/code]

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.