Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a character is alphabetic

Tags:

validation

php

Having problems with this.

Let's say I have a parameter composed of a single character and I only want to accept alphabetic characters. How will I determine that the parameter passed is a member of the latin alphabet (az)?

By the way Im using PHP Kohana 3.

Thanks.

like image 946
Ed. Avatar asked Feb 09 '10 05:02

Ed.


People also ask

How can you tell if a character is alphabetic?

C isalpha() The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.

What is an example of an alphabetic character?

Alphanumeric characters are the numbers 0-9 and letters A-Z (both uppercase and lowercase). An alphanumeric example are the characters a, H, 0, 5 and k.

How do you check whether a character is alphabet or not in Python?

Python String isalpha() The isalpha() method returns True if all characters in the string are alphabets. If not, it returns False.

How do you check if a character is a letter or digit?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.


2 Answers

http://php.net/manual/en/function.ctype-alpha.php

<?php
    $ch = 'a';
    if (ctype_alpha($ch)) {
        // Accept
    } else {
        // Reject
    }

This also takes locale into account if you set it correctly.

EDIT: To be complete, other posters here seem to think that you need to ensure the parameter is a single character, or else the parameter is invalid. To check the length of a string, you can use strlen(). If strlen() returns any non-1 number, then you can reject the parameter, too.

As it stands, your question at the time of answering, conveys that you have a single character parameter somewhere and you want to check that it is alphabetical. I have provided a general purpose solution that does this, and is locale friendly too.

like image 71
Nick Presta Avatar answered Oct 08 '22 05:10

Nick Presta


Use the following guard clause at the top of your method:

if (!preg_match("/^[a-z]$/", $param)) {
    // throw an Exception...
}

If you want to allow upper case letters too, change the regular expression accordingly:

if (!preg_match("/^[a-zA-Z]$/", $param)) {
    // throw an Exception...
}

Another way to support case insensitivity is to use the /i case insensitivity modifier:

if (!preg_match("/^[a-z]$/i", $param)) {
    // throw an Exception...
}
like image 26
Asaph Avatar answered Oct 08 '22 07:10

Asaph