XML technologies / Regular expressions / PHP / The preg functions / preg_quote

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

preg_quote(input [, begrenzer ])

Parameters

input

A string to be treated as literal text in a pattern argument (see The pattern parameter).

begrenzer

An optional string of exactly one character, used as the delimiter in the pattern argument.

Return value

preg_quote produces a version of input in which the regex metacharacters are escaped. If begrenzer is specified, that character is escaped too.

Explanation

A string intended as literal text in a regex should be processed with preg_quote so its characters are not interpreted as regex metacharacters. You can also specify the delimiter you will use, which will be escaped too.

Function preg_quote is quite specialized and seldom needed, but here is an example:

/* E-Mails mit $MailBetreff in der Subject:-Zeile herausfiltern */
$pattern = '/^Subject:\s+(Re:\s*)*' . preg_quote($MailBetreff, '/') . '/mi';

If $MailBetreff contains text such as

**Sonderangebot** (Jetzt zugreifen!)

, then $pattern receives value

/^Subject:\s+(Re:\s*)*\*\*Sonderangebot\*\* \(Jetzt zugreifen\!\)/mi

, which can safely be used in a preg function’s pattern argument.

If begrenzer is ‘{’ or another paired delimiter, only that character is escaped, not its counterpart (‘}’). Use only unpaired delimiters for this purpose.

Also, neither whitespace nor ‘#’ is escaped, so the result is unsuitable for matching with modifier x.

Overall, preg_quote is only a partial solution for handling arbitrary literal text in a PHP regex. It solves only the text-to-regex problem, not the regex-to-pattern-argument step required for general use with preg functions. A solution is developed in “Missing” preg functions.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top