Escaping

There may be instances where you want to include literal characters in patterns that are usually interpreted as meta-characters. This can be accomplished via a \ metacharacter.

<?php
// Matches literal [
$matches = (preg_match('/\[/', $string) == 1);

// Matches literal 1
$matches = (preg_match('/\\/', $string) == 1);

// Matches expression delimiter /
$matches = (preg_match('/\//', $string) == 1);

// Matches any of the standard escape sequences 1r, 1n, or 1t
$matches = (preg_match('/\r|\n|\t/', $string) == 1);
?>

Note that it is necessary to double-escape " in the second example because the string ’

' is interpreted to be a single backslash by PHP whether or not it is used in a regular expression. In other cases, no escaping of ” is needed for the escape sequence to be interpreted properly.

Double Escaping

For more information on the reasoning behind the double-escape example in this section, see http://php.net/manual/en/language.types.string.php#language.types.string and the Backslash section of http://php.net/manual/en/regexp.reference.php.


© PCRE Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (03.09.2014)
Views: 337 | Rating: 0.0/0
Total comments: 0
avatar