PHP 7.0.6 Released

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:

Meta-characters outside square brackets
Meta-characterDescription
\general escape character with several uses
^assert start of subject (or line, in multiline mode)
$assert end of subject or before a terminating newline (or end of 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 makes greedy quantifiers lazy (see repetition)
*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:
Meta-characters inside square brackets (character classes)
Meta-characterDescription
\general escape character
^negate the class, but only if the first character
-indicates character range
The following sections describe the use of each of the meta-characters.

User Contributed Notes

Kurt Wei
2 months ago
disturbing usage of "any character" for multi-lines...

remark:
'.' (all characters) just does NOT include on single character the newline (\n) by default,
while \n is included in all other matching searches (e.g. \s).
Funny enough, the "carriage return" (\r) is included, when using '.'

You have to write "(.|\\n)" instead of a single dot, with disadvantages in using complex matching-results,

or simple use the "s" modificator to bring dot to accept the newline.

$subject="<tag>Hello\nWorld</tag>";

preg_match( '/<tag>[A-Za-z\\s]*<\\/tag>/' , $subject ); //true
preg_match( '/<tag>[^<]*<\\/tag>/' , $subject ); //true
preg_match( '/<tag>(.|\\n)*<\\/tag>/' , $subject ); //true
preg_match( '/<tag>.*<\\/tag>/s' , $subject ); //true
preg_match( '/<tag>.*<\\/tag>/' , $subject ); //ATTENTION! *false*
Thomas
1 year ago
The meta character $ accepts a (one) newline character (\n).

(Take a moment to let this information sink in)

You might want to (r)trim() your input afterwards if you have a match because otherwise it (still) might not meet a length requirement or other strange stuff might happen when you store the input as-is.
To Top