The regular expressions basic syntax
To use regular expressions first you need to learn the syntax of the patterns. We can group the characters inside a pattern like this:
1 Start and end indicators as ^ and $
2 Count indicators like +,*,?
3 Logical operator like |
4 Grouping with {},(),[]
5 \ is used as a general escape character
A basic example would looks like this:
if (preg_match('/tutorial/', 'tips and tutorials are very useful'))
echo "word 'tutorial' found!";
Now let's see a detailed pattern syntax reference:
1 "ab*": matches a string that has an a followed by zero or more b's ("a", "ab", "abbb", etc.);
2 "ab+": same, but there's at least one b ("ab", "abbb", etc.);
3 "ab?": there might be a b or not;
4 "a?b+$": a possible a followed by one or more b's ending a string.
5 "ab{2}": matches a string that has an a followed by exactly two b's ("abb");
6 "ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
7 "ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
8 "a(bc)*": matches a string that has an a followed by zero or more copies of the sequence "bc";
9 "a(bc){1,5}": one through five copies of "bc."
10 "hi|hello": matches a string that has either "hi" or "hello" in it;
11 "(b|cd)ef": a string that has either "bef" or "cdef";
12 "(a|b)*c": a string that has a sequence of alternating a's and b's ending in a c;
13 "a.[0-9]": matches a string that has an a followed by one character and a digit;
14 "^.{3}$": a string with exactly 3 characters.
15 "[ab]": matches a string that has either an a or a b (that's the same as "a|b");
16 "[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal to "a|b|c|d" and even "[abcd]");
17 "^[a-zA-Z]": a string that starts with a letter;
18 "[0-9]%": a string that has a single digit before a percent sign;
19 ",[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.
------------------------------------------------------------------------------------------
An example pattern to check valid emails looks like this:
^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$
The code to check the email using Perl compatible regular expression looks like this:
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$email = "jim@demo.com";
if (preg_match($pattern,$email)) {
echo "Match";
}
else {
echo "Not match";
}
Hope this helps .
0 Responses to "PHP regular expression tutorial"
Post a Comment