PHP preg_quote() Function

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

The preg_last_error function is used to escape regular expression characters.

Syntax

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() requires the parameter str and adds a backslash before each character in regular expression syntax. This is typically used when you have runtime strings that need to be matched as regular expressions.

The regular expression special characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parameter description:

  • $str: Input string.

  • $delimiter: If the optional parameter delimiter is specified, it will also be escaped. This is typically used to escape the delimiters used by PCRE functions. / is the most common delimiter.

Return Value

Returns the escaped string.

Examples

Example 1

<?php $keywords = '$40 for a g3/400'; $keywords = preg_quote($keywords, '/'); echo $keywords; ?>

The execution result escapes the $ and / special characters, as shown below:

返回 \$40 for a g3\/400


Replace words in text with italic

<?php //In this example, preg_quote($word) is used to preserve the literal meaning of the asterisk, so that it does not use special semantics from regular expressions. $textbody = "This book is *very* difficult to find."; $word = "*very*"; $textbody = preg_replace ("/" . preg_quote($word) . "/", "<i>" . $word . "</i>", $textbody); echo $textbody; ?>

The execution result is as follows:

This book is <i>*very*</i> difficult to find.

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

Other Extensions