preg_quote
Escapes regular expression special characters.
Syntax
preg_quote(string $str, ?string $delimiter = null): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $str | string | The string to put into a pattern. |
| $delimiter | ?string | Optional. The pattern delimiter, usually `/`. |
Return value
stringThe string with characters escaped.
Examples
Searching for text typed by a user:
<?php
$search = '1+1 (sum)';
$pattern = '/' . preg_quote($search, '/') . '/';
echo $pattern, "\n";
echo preg_match($pattern, 'Result of 1+1 (sum) is 2');Output:
/1\+1 \(sum\)/
1Notes
Without escaping, +, (, . and other characters would act as parts of the pattern.
See also
- preg_match — Tests a string against a regular expression.
- preg_replace — Replaces everything that matches a regular expression.
- addslashes — Adds a backslash before quotes.
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.