In this previous lesson, I introduce you the very basic regular expressions.
This second part is even more interesting than the previous one.
In this time, I want to introduce one the most useful character in use
in regular expression is
[]. Everything between the
[ and
] are optional
characters. For example:
"^[ab]" which mean that it could be start with
letter
a or
b, Another example:
"^[abcd]" which mean it could be start
with letter from a to d. How about if you want to match any string that begin
with any letter between a and h, so it would be like this
"^[abcdefgh]"
But you can do it in another way by using the character -. Instead
of using
"^[abcdefh]", you can use
"^[a-h]". What if you want to
match everything that start with english alphabet, you can probally
write like this
"^[a-z]" but it is only match the lowercase alphabet. To
match both lowercase and uppercase you can simply do like this
"^[a-zA-Z]".
Similar to alphabet, you can do like this to the number.
For example:
"^[0-9]" match with any string that start with number.
Here are the example using regular expressions with PHP:
PHP Code:
<?php
$regexp = "^[a-zA-Z][0-9]$";
$string = "h1";
if (ereg($regexp, $string)) {
print "Match...!";
} else {
print "Not Match...!";
}
?>
This example match only the string that begin with single alphabet and
single number.
"hh1" or
"h11" is not matched. But if you want to
match any string that begin with letters and end with numbers.
You can use
+, which is already mention in previous lesson.
PHP Code:
<?php
$regexp = "^[a-zA-Z]+[0-9]+$";
$string = "HelloWorld2000";
if (ereg($regexp, $string)) {
print "Match...!";
} else {
print "Not Match...!";
}
?>
Right now, I want to right one program that allow users to insert their
real name. Before I let their realname get into my database, I will check
first in case it is spam or is it a correct name format. Usually real name
are probally in alphabet no number and no special character. The only
special characters that allow are
blank space,
' and
- So it is how
I check.
PHP Code:
$regexp = "^[A-Za-z][A-Za-z' -]$";
if (ereg($regexp, $realname)) {
// Insert the realname into database
} else {
// Warn them to inser the correct realname
}
In this code, I will allow only string that begin with alphabet and follow by
other alphabets and 3 other special charracters that we allow.
In this lesson, you have learn about
[] which is very useful for using
to apply to real application. Hopefully, you enjoy this second part.
I promise that in 3rd part it's going to be more interesting than
first and second one. Enjoy!!! Comments please
From siLenTz
Woho....