PHP preg_quote() Function
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() takes the parameter str and adds a backslash before each regex metacharacter in it. This is typically used when you have some runtime strings that need to be matched as regular expressions.
Special regex characters include: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Parameter Description:
$str: The input string.
$delimiter: If the optional parameter delimiter is specified, it will also be escaped. This is typically used to escape delimiters used by PCRE functions. / is the most common delimiter.
Return Value
Returns the escaped string.
Example
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:
Returns \$40 for a g3\/400
Replace Words in Text with Italics
<?php
// In this example, preg_quote($word) is used to preserve the literal meaning of asterisks, preventing them from being interpreted as special regex characters.
$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 shown below:
This book is <i>*very*</i> difficult to find.