preg_quote()
preg_quote() — Quote regular expression characters.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
Signature
preg_quote(string $str, ?string $delimiter = null): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $str | string | The input string. |
| $delimiter | ?string | If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter. |
Return value
Returns the quoted (escaped) string.
Example
A runnable snippet:
$keywords = '$40 for a g3/400'; $keywords = preg_quote($keywords, '/'); echo $keywords; // returns \$40 for a g3\/400
Changelog
| Version | Change |
|---|---|
| 7.3.0 | The # character is now quoted |
| 7.2.0 | delimiter is nullable now. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page preg_quote() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.