Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

How can I deturmine if a string contains any letters or numbers?

Hello.

How can I deturmine if a string contains any letters or numbers?


Right now I am using this:

       if ($string != null) { echo "contains text"; }

But if the string has only spaces and new lines in it, the script returns "contains text"
I want it to do this only if there are letters or numbers in the string.

Thanks!
Avatar of hernst42
hernst42
Flag of Germany image

You can try:

if (strlen(trim($string)) > 0) { echo "contains text.";}

trim removes any whitespace at the end and beginning of a string.
Avatar of cLFlaVA
cLFlaVA

Try this:

if(ereg('[^A-Za-z0-9]', $string)){
    echo "String must contain only letters and numbers.";
}else{
    echo "$string has only letters and numbers.";
}
Avatar of hankknight

ASKER

Thanks!

       if (strlen(trim($string)) > 0) { echo "contains text.";}

would work exept if my string contains funny characters ( ., ?, *, ©, etc ) it would still pass the test.

The ereg option is closer:

        if(ereg('[^A-Za-z0-9]', $string)){
            echo "String must contain only letters and numbers.";
        }else{
            echo "$string has only letters and numbers.";
        }

But this tells me if the string contains anything other than letters and numbers.  I want to find out if the string contains at least one letter or one number.
ASKER CERTIFIED SOLUTION
Avatar of cLFlaVA
cLFlaVA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial