I will try to write here a little tutorial about how to write regular expressions with PHP.
Basic syntacs.
This is a list of the basic used symbols with patterns, but there are and more, see also what
O'Rielly Pocket Reference says.
Special symbol:
^ . It matches any string that starts with a given pattern.
Some example here:
'^ojo' - here matches the strings, that starts with
'ojo'.
Special symbol:
$ . It matches any string that ends with a given pattern.
Some example here:
'bojo$' - here matches the strings, that end with
'bojo'.
Special symbol:
| . It matches any string that has one from two given values, it works like OR operator.
Some example here:
'hey|hi' - matches a string that has either "hey" or "hi" in it.
Special symbol:
. (period) . It matches any string that has one from two given values, it works like OR operator.
Some example here:
'a.' - matches a string that has at least a or a and one more symbol.
Special symbols:
*, +, ?. They denote the number of times a character or a sequence of characters may occur. What they mean is: "zero or more", "one or more",
Some examples here:
'ojo*' - here matches a string that has an 'oj' followed by zero or more o's (
'oj',
'ojo',
'ojoooo' and so on).
'ojo+' - matches a string that has at least one o(
'ojo',
'ojoo' and so on).
'ojo?' - there might be
'ojo' or not.
More complex examples.
I will try here to add some useful patterns, the list will be expand next days.
If you use them together
'^' and
'$', it is obviously that it is equal to the exact pattern, I mean that if you say you want
'^ohoboho$', it is equal to
'ohoboho'.
'oho{2}' - matches a string that has an a followed by exactly two o's (
"ohoo");
'oho{2,5}' - matches a string that has an a followed by two to five o's;
'oho{2,}' - matches a string that has at least two to five o's;
'^[a-zA-Z]{3,5}' - matches a string that starts with a string from 3 to 5 letters long;
'^[+]?\d*$' or
'^[0-9]+$' or
' ^\d*$' - matches used for set numbers only (here
'\d' means digit character, [0-9]);
'^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$' - matches for correct email;
'^[a-zA-Z0-9-.]+.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$' - tests the validity of a domain or hostname. It will match any valid domain name that does not contain characters which are invalid in URLs, and which ends in .com, .org, .net, .mil, or .edu.;
Pattern-Matching Functions.
PHP provides several standalone functions for pattern matching. When creating regular expression strings, you need to escape embedded backslashes; otherwise, the backslash is interpreted in the string before being sent to the regular expression engine.
Regular Expression Functions (Perl-Compatible)
Sources:
PHP Regular Expressions (O'Rielly Pocket Reference)
Regular Expression Library
category: Web development, posted date: 04.06.2006, [2]
As you see, here we write in english... That's why Ivaylo, I will ask you to keep the rules. Greetings, Raya :)