preg_quote() is what you are looking for:

Description

string preg_quote ( string $str [, string $delimiter = NULL ] )

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.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parameters

str

The input string.

delimiter

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.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

Example - using preg_match to find occurrences of a given URL surrounded by whitespace:

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }
Answer from Tom Haigh on Stack Overflow
🌐
PHP
php.net › manual › en › function.preg-quote.php
PHP: preg_quote - Manual
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E. For example: <?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?> Will result in: match But: <?php echo ( preg_match('/^\Q'.( ...
Top answer
1 of 2
280

preg_quote() is what you are looking for:

Description

string preg_quote ( string $str [, string $delimiter = NULL ] )

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.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parameters

str

The input string.

delimiter

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.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

Example - using preg_match to find occurrences of a given URL surrounded by whitespace:

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }
2 of 2
2

It would be much safer to use Prepared Patterns from T-Regx (i'm the author of the library):

$url = 'http://stackoverflow.com/questions?sort=newest';

$pattern = Pattern::inject('\s@\s', [$url]);
                                    // ↑ $url is quoted

then perform normal match:

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";

$matcher = pattern->match($haystack);
foreach ($matcher as $match) {
}

you can even use it with preg_match():

preg_match($pattern, 'foo', $matches);
🌐
MojoAuth
mojoauth.com › escaping › regex-escaping-in-php
Regex Escaping in PHP | Escaping Methods in Programming Languages
When working with regex escaping in PHP, following best practices can significantly reduce errors and improve code readability: Always Escape Special Characters: Ensure that any special characters that should be treated literally are escaped.
🌐
BrainBell
brainbell.com › php › escaping-special-characters-in-regular-expressions.html
Escaping special characters in regular expressions in PHP – BrainBell
Escape the string with preg_quote() function in the pattern: <?php $string = 'Hi, 2+3 is equal to 5'; $find = preg_quote('2+3'); $pattern = '/'.$find.'/'; $found = preg_match($pattern, $string, $match);# true print_r($match); // 2+3 · The preg_quote() function is particularly useful when you ...
🌐
O'Reilly
oreilly.com › library › view › php-cookbook › 1565926811 › ch13s09.html
13.8. Escaping Special Characters in a Regular Expression - PHP Cookbook [Book]
November 20, 2002 - You want to have characters such as * or + treated as literals, not as metacharacters, inside a regular expression. This is useful when allowing users to type in search strings you want to use inside a regular expression. Use preg_quote( ) to escape Perl-compatible regular-expression metacharacters:
Authors: David SklarAdam Trachtenberg
Published: 2002
Pages: 640
🌐
SSOJet
ssojet.com › escaping › regex-escaping-in-php
Regex Escaping in PHP | Escaping Techniques in Programming
PHP's preg_quote() function is designed for this exact purpose. It automatically escapes any characters within a string that have special meaning in regular expressions, ensuring they're treated as literal characters.
🌐
Designcise
designcise.com › web › tutorial › how-to-escape-regular-expression-special-characters-in-php
How to Escape Regex Special Chars in PHP? - Designcise
June 4, 2021 - You can use the backslash character (i.e. \) to escape the regular expression special characters. For example: $str = 'hello?'; $replaceWith = 'hey?'; $pattern = '/hello\?/'; echo preg_replace($pattern, $replaceWith, $str); // 'hey?'
🌐
DocStore
docstore.mik.ua › orelly › webprog › pcook › ch13_09.htm
Escaping Special Characters in a Regular Expression (PHP Cookbook)
You want to have characters such as * or + treated as literals, not as metacharacters, inside a regular expression. This is useful when allowing users to type in search strings you want to use inside a regular expression · Use preg_quote( ) to escape Perl-compatible regular-expression ...
Find elsewhere
🌐
Code.mu
code.mu › en › php › book › prime › regular › escaping-special-characters
Escaping Special Characters in PHP Regex
Suppose we want a special character to represent itself. To do this, it must be escaped with a backslash. Let's look at some examples. In the following example, the regex author wanted the search pattern to look like this: the letter 'a', then a plus '+', then the letter 'x'. However, the code ...
🌐
SitePoint
sitepoint.com › php
Correct rules for escaping special characters in a preg_match() - PHP - SitePoint Forums | Web Development & Design Community
July 3, 2022 - I am trying to learn how to use preg_match() and already I am having problems understanding the logic. At the moment I am exploring searching for special characters using escapes. I have established that the special characters that need escaping are . \ + * ? [ ^ ] $ ( ) { } = ! | : - All good so far as in if (preg_match("/\?/", $string)) {... But if I search for a \ then I need to escape it with a \\as in if (preg_match("/\\\/", $string)) {... Ok, I can accept that as a special case but...
🌐
SitePoint
sitepoint.com › php
Regex for Special Characters - PHP - SitePoint Forums | Web Development & Design Community
July 5, 2012 - I have some questions about the Regex below… // Check for Special-Character. if (empty($errors)){ if (!preg_match("#[\\~\\`\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\-\\+\\=\\{\\}\\[\\]\\|\\:\\;\\&lt;\\&gt;\\.\\?\\/\\\\\\\…
🌐
GeeksforGeeks
geeksforgeeks.org › php › function-to-escape-regex-patterns-before-applied-in-php
Function to escape regex patterns before applied in PHP - GeeksforGeeks
July 12, 2025 - <?php // Create a string which need to be escaped $str = "Welcome to GfG! (+ The course fee. $400) /"; echo "Before Processing - " . $str . PHP_EOL; // Use preg_quote() on above string $processedStr = preg_quote($str); // Display the output echo "After Processing - " . $processedStr; ?> ... Before Processing - Welcome to GfG! (+ The course fee. $400) / After Processing - Welcome to GfG\! \(\+ The course fee\. \$400\) / Notice that a backslash was put in front of every special character, but not for the forward slash.
🌐
Code.mu
code.mu › en › php › book › prime › regular › auto-special-escaping
Automatic Escaping of Special Regex Characters in PHP
In this lesson, we will study the function that escapes special regular expression characters in PHP.
🌐
Regular-Expressions.info
regular-expressions.info › php.html
Using Regular Expressions with PHP
In PHP, this becomes preg_match('/regex/', $subject). When forward slashes are used as the regex delimiter, any forward slashes in the regular expression have to be escaped with a backslash. So https://www\.regexp\.info/ becomes '/https:\/\/www\.regexp\.info\//'. Just like Perl, the preg functions ...
🌐
Code.mu
code.mu › en › php › book › prime › regular › special-characters-list
List of Special Characters in Regex in PHP
Write a regex that will find the strings inside square brackets and replace them with '!'.