Validating Forms and Regexes:
Regular expressions provide advanced string matching and manipulation. A regular expression is basically a pattern that describes the string wanted. Once you learn them in PHP, you can apply them with slight modifications to other programming languages such as Perl, JavaScript, etc. Throughout this article, I will refer to them as "regexes". Shall we begin? NOTE: this is not a crash course in regular expressions, yet a mere beginning.

In PHP there are two functions that handle regexes, ereg() and eregi(). ereg() is case sensitive while eregi() is not. I suggest you visit PHP.net and look up these functions for there correct usage.

^programming
The special character ^ indicates that the string should begin with the pattern "programming"; so "programming is fun" would match the pattern, but "I love programming" would not.

programming$
In this pattern, the special character $ indicates that a string should end with the pattern "programming"; thus "I love programming" would match the pattern.

^programming$
^ and $ used together will match exact strings. In this case, only "programming" would match.

programming
This pattern will match any string that contains "programming" in it.
For more complex characters such as whitespace and punctuation, we use what are called escape sequences. Most punctuation marks can be represented by a backslash preceding the puctuation mark e.g. \. A list of common escape sequences follow:

-\f represents a form feed
-\n represents a newline
-\r represents a carriage return
-\t represents a tab

Say were were trying to validate our sample form above. We need a way to closely describe the values we want. Character classes do just this.

[AaNnDdRrEeWw]
This will return true if the character being considered in the class can be found. Character classes match only one character unless told otherwise. We could use a hyphen to represent a range like in math:

[a-z] # match any lowercase letter
[A-Z] # match any uppercase letter
[a-zA-Z] # match any letter
[0-9] # match any digit

^'s used within character classes means not:
[^a-zA-Z] # would not match a letter
-- Continued...3
Sponsored Links: