Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

preg_quote

Escapes regular expression special characters.

Syntax

preg_quote(string $str, ?string $delimiter = null): string

Parameters

ParameterTypeDescription
$strstringThe string to put into a pattern.
$delimiter?stringOptional. 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\)/
1

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.