Wednesday, October 14, 2009

PHP Regular Expression Tutorial

PHP regular expression tutorial

PHP Regular Expressions seems to be a quite complicated. Regular Expressions can easy find a pattern in a string and/or as a replacer.

Basic Syntax of Regular Expressions

Meta-characters
The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are

encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square

brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\   -  general escape character with several uses
^  -  assert start of subject (or line, in multiline mode)
$  -  assert end of subject (or line, in multiline mode)
.   -  match any character except newline (by default)
[   -  start character class definition
]   - end character class definition
|   -  start of alternative branch
(  - start subpattern
)   - end subpattern
?  - extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer
*  - 0 or more quantifier
+  - 1 or more quantifier
{  - start min/max quantifier
} - end min/max quantifier
Part of a pattern that is in square brackets is called a "character class". In a character class the only meta-characters are:

\     -  general escape character
^    -  negate the class, but only if the first character
-     -  indicates character range
]     -  terminates the character class
The following sections describe the use of each of the meta-characters.

Backslash
The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special

meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following

character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to

specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and

characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a     -    alarm, that is, the BEL character (hex 07)
\cx   -   "control-x", where x is any character
\e    -   escape (hex 1B)
\f     -   formfeed (hex 0C)
\n    -   newline (hex 0A)
\r    -   carriage return (hex 0D)
\t    -  tab (hex 09)
\xhh  -  character with hex code hh
\ddd  -  character with octal code ddd, or backreference
The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the

character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040  -  is another way of writing a space
\40   - is the same, provided there are fewer than 40 previous capturing subpatterns
\7    -  is always a back reference
\11  -  might be a back reference, or another way of writing a tab
\011 -  is always a tab
\0113 -  is a tab followed by the character "3"
\113  -  is the character with octal code 113 (since there can be no more than 99 back references)
\377  -  is a byte consisting entirely of 1 bits
\81  -  is either a back reference, or a binary zero followed by the two characters "8" and "1"
Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the ackspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d   -  any decimal digit
\D   -  any character that is not a decimal digit
\s   -   any whitespace character
\S  -  any character that is not a whitespace character
\w  -  any "word" character
\W  -  any "non-word" character
Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters,
and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b  -  word boundary
\B  -  not a word boundary
\A  -  start of subject (independent of multiline mode)
\Z  -  end of subject or newline at end (independent of multiline mode)
\z  -  end of subject (independent of multiline mode)
\G  -  first matching position in subject
These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of
the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero. It is available since PHP 4.3.3. \Q and \E can be used to ignore regexp metacharacters in the pattern since PHP 4.3.3. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

Examples :
^Quit           -          Matches any string that starts with "Quit"
^ouch$        -          String that starts and ends with "ouch"
foo              -          Matches a string "foo"
foo$            -          "foo" at the end of a string
^foo$          -          "foo" when it is alone on a string
[abc]           -          a, b, or c
[a-z]            -          Any lowercase letter
[^A-Z]        -          Any character that is not a uppercase letter
(gif|jpg)        -          Matches either "gif" or "jpeg"
[a-z]+          -          One or more lowercase letters
[0-9\.\-]       -          Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$          -         Any word of at least one letter, number or _
([wx])([yz])          -         wy, wz, xy, or xz
[^A-Za-z0-9]      -         Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})         -         Matches three letters or four numbers
apple*         -       Matches a string like ("apple", "appleee", "appl" etc..) - 0 or more e's
apple+         -       Matches a string like ("apple", "appleee", etc..) - 1 or more e's
apple?         -       Matches a string like ("apple", "appl") - 0 or 1
we{3}         -       Matches a string that has an a followed by exactly three e's ("weee")
we{,3}        -      Matches a string at least three e's ("weee", "weeee", etc)
we{3,5}      -      Matches a string from three to five e's ("weee", "weeee", etc)


For more info refer to http://www.php.net/ site. Click here.

Related Posts




No comments:

Post a Comment