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 (a
–z
)?
By the way Im using PHP Kohana 3.
Thanks.
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.
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.
Python String isalpha() The isalpha() method returns True if all characters in the string are alphabets. If not, it returns False.
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.
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.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With