PHP Reference ยท Regular Expressions
PHP preg_quote() function
Reference for PHP preg_quote(): escape regular expression special characters so user text is matched literally, why the delimiter argument matters, and what it escapes.
The preg_quote() function puts a backslash in front of every character that has a special meaning in a regular expression. Run text through it before you build a pattern from a variable, and the engine will look for that text literally instead of interpreting ., *, ( or ? as syntax.
Always pass the delimiter of your pattern as the second argument. preg_quote() cannot know which character you chose, so it will not escape / (or #, ~...) unless you tell it.
<?php echo preg_quote('1+1=2 (really?)', '/');
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
preg_quote(string $str, ?string $delimiter = null): string
| Name | Description |
|---|---|
$str |
The text to escape. |
$delimiter |
Optional. A single character that is also escaped; pass the delimiter you use in the pattern. |
Return value: the escaped string.
Escaped characters: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #, plus the delimiter you pass (so / is escaped only when you ask for it). The NUL byte becomes \000. Since PHP 7.3, # is escaped too.
Errors / Exceptions: none for normal strings.
Usage notes
- Pass the delimiter. A forgotten second argument is the classic bug: user text containing
/ends the pattern early and either breaks it or changes its meaning. - It escapes for the pattern, not for the replacement. In
preg_replace()replacements,$1and\1are special; protect untrusted replacement text withpreg_replace_callback()or escape$and\yourself. - Not needed for plain substring tests.
str_contains(),strpos()andstr_replace()never interpret special characters; reach for a regex only when you need pattern features. - Inside a character class
[...],preg_quote()is still safe, because-,^and]are among the escaped characters. - Whitespace is not escaped. If you use the
xmodifier (extended mode), spaces and#in the quoted text would be ignored or start a comment; escape them yourself or avoidxfor quoted parts. - It works on bytes. Multibyte UTF-8 text passes through unchanged, which is correct when you also use
/u. - Quoting a whole pattern is a mistake: quote only the variable pieces, then add your own syntax around them.