5.8 Checking Characters


5.8 Checking Characters

You want to check whether a value contains only alphabetic characters.

Technique

Use eregi () in conjunction with character classes:

 <?php if (eregi ("^[a-z]+$", $line)) {     // .. do if true } else {     // .. do if false } ?> 

Or use the predefined character class along with ereg() :

 <?php if (ereg ("^[[:alpha:]]+$", $line)) {     // .. do if true } else {     // .. do if false } ?> 

Comments

In the first solution, we use eregi() , which performs a case-insensitive query using a specified pattern (in this case, [a-z] ). As discussed in the introduction, the regular expression [a-z] is a character class that will match any lowercase letter from a to z. Because we are using a case-insensitive search, [a-z] will match any character. We put a plus after the [a-z] character class to indicate that there must be one or more occurrences. The entire regular expression is enclosed within ^ and $ , meaning that the entire string must match the pattern (this is also discussed in the introduction).

In the second solution, we simply substitute eregi() (case-insensitive) with ereg() (case-sensitive), and instead of [a-z] we use [[:alpha:]] which is a predefined character set that matches any alphabetic character. PHP provides several of these predefined character classes, listed in the following table.

Name Description
[[:alnum:]] All alphanumeric characters [a-zA-Z0-9]
[[:alpha:]] All alphabetic characters [a-z]
[[:blank:]] Tab and space [\t ]
[[:cntrl:]] All the control characters
[[:digit:]] All decimal digits [0-9]
[[:graph:]] All printable characters except space
[[:lower:]] All lowercase letters [a-z]
[[:print:]] All printable characters
[[:punct:]] Punctuation marks [\.,;:-]
[[:space:]] All whitespace characters
[[:upper:]] All the uppercase letters [A-Z]
[[:xdigit:]] The set of hexadecimal digits

These are just easy ways to access commonly used character classes. To negate reserved classes, make sure that you put the ^ inside the first bracket :

 [^[:space:]] // Match anything that isn't a space 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net