PHP Regular Expressions Literal Characters
Description
The simplest form of regular expression pattern is a literal string.
The string stored in the pattern matches the same string of characters in the target string, with no additional rules applied.
Syntax
The syntax to create PHP regular expressions literal characters is to wrap the leteral value in double quote.
"hello" are treated as literal strings in regular expressions. The string "hello" in a regular expression matches the text "hello" in the target string.
Escape
Digits, spaces, single and double quotes, and the % , & , @ , and # symbols are treated literally by the regular expression engine.
Some characters have special meanings within regular expressions. These nineteen special characters are:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | :
If you want to include any character from this list literally within your expression, you need to escape it by placing a backslash ( \ ) in front of it, like so:
<?PHP
echo preg_match( "/PHP\?/", "What is PHP?" );
?>
In addition, if you use your delimiter character within your expression, you need to escape it:
<?PHP
echo preg_match( "/http\:\/\//", "http://www.example.com" ); // Displays "1"
?>
By using a different delimiter, such as the | (vertical bar) character, you avoid having to escape the slashes within the expression:
<?PHP
echo preg_match( "|http\://|", "http://www.example.com" ); // Displays "1"
?>
Various characters literally
Various characters literally within regular expressions by using escape sequences.
Escape Sequence | Meaning |
---|---|
\n | A line feed character (ASCII 10) |
\r | A carriage return character (ASCII 13) |
\t | A horizontal tab character (ASCII 9) |
\e | An escape character (ASCII 27) |
\f | A form feed character (ASCII 12) |
\a | A bell (alarm) character (ASCII 7) |
\xdd | A character with the hex code dd (for example, \x61 is the ASCII letter "a" ) |
\ddd | A character with the octal code ddd (for example, \141 is the ASCII letter "a" ) |
\c x | A control character (for example, \cH denotes ^H , or backspace) |
Escape Example
To escape use \.
$ is a regexp symbol we can precede it with a \, and we turn the $ into a standard character and not a regexp symbol.
This next regexp shows two character classes, with the first being required and the second optional.
<?PHP
preg_match("/\$[A-Za-z_][A-Za-z_0-9]*/", "Java");
?>