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 SequenceMeaning
\nA line feed character (ASCII 10)
\rA carriage return character (ASCII 13)
\tA horizontal tab character (ASCII 9)
\eAn escape character (ASCII 27)
\fA form feed character (ASCII 12)
\aA bell (alarm) character (ASCII 7)
\xddA character with the hex code dd (for example, \x61 is the ASCII letter "a" )
\dddA character with the octal code ddd (for example, \141 is the ASCII letter "a" )
\c xA 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");
?>




















Home »
  PHP Tutorial »
    Development »




Environment
Error
Hash
Include
Locale
Math
Network
Output
Reflection
PHP Regular Expressions