This is my first tutorial in this forum. In this tutorial, I will introduce you
to the basic of regular expressions in PHP. Some of you know what is it
and some are don't.
Regular expressions is pattern string descibe
the match to other string. It is very powerful too for use to filter the
string that is not in format that you want.
First of all, let me introduce you to
^ in regular expression.
^, this special
character in regular expression mean the beginning of the string.
If the regular expression is
^a so it will match to any string that start with
letter
a. Now let apply this regular expression into PHP code.
PHP Code:
<?php
$regexp = "^a";
$string = "apple";
if (ereg($regexp, $string)) {
print "Match...!";
} else {
print "Not Match...!";
}
?>
ereg is php function that is search for string that is matched with regular
expression. In this code my regular expression is
"^a", which mean
every string that start with letter
a will be matched. So
"apple" is string
that start with letter
a which is matched. Now if the
$string = "boy" then
the string is not matched because it is started with letter
b. Pretty simple
right?
Contrasting with
^,
$ mean end of the string. For example:
"t$" mean
that any string, that has letter
t at the end of the string, is matched.
PHP Code:
<?php
$regexp = "t$";
$string = "eat";
if (ereg($regexp, $string)) {
print "Match...!";
} else {
print "Not Match...!";
}
?>
The string
"eat" is matched but if
$string = "network", it is not matched.
How about this regular expression,
"^apple$"? What dose it mean?
It probally mean any string that start with word
apple and end with word
apple, so it mean any string that contain exactly only word
"apple" is
matched.
"applez" or
"aapple" is not mathced.
+ mean one or more. For example:
"^a+" mean at least there are one or
more a letter at the beginning of string. strings, that are matched this
expression, are
"a",
"aa",
"aaa". Another example:
"a+$" mean at least
one or more of letter a are at the end of the string.
NOTE: What is
"a" mean if we don't use any special character? It
mean any string that contain one or more a letter will be match
for example:
"apple" Matched,
"eat" Matched,
"fix" not matched.
This is my first lesson for regular expression, and more interesting thing
will continue in the second part... I hope you enjoy it. Comment
are warmly welcome.
From siLenTz
Regular expressions RULE...