PHP preg_quote() Function

What is PHP preg_quote() function?

Suppose you’re searching for a character in a string that has special meaning in regular expression (ex. ? or *) using any regular expression functions. You can’t find the match until you escape this character. PHP preg_quote() function helps to accomplish this (Check Example 3).. This function takes a string and by adding a backslash in front of a special character, the function escapes that character and return you the same string (Check Example 1).

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : – #. If you don’t escape these characters from regular expression pattern with preg_quote() function, these characters becomes part of regular expression and returns you an incorrect result (Check Example 4).

Syntax:

preg_quote(input, delimiter)

Parameters:

Input (Mandatory): It is a string that you want to escape.

delimiter (Optional): It is a single character. If you want to escape a character that is not a part of a special regular expression character, mention this as a delimiter (Check Example 2).

Return Values:

preg_quote() function returns the quoted (escaped) string (Check Example 1).

Examples:

Example 1:

<?php
$input = 'preg_quote()';
$return_value = preg_quote($input);
echo $return_value; // Output: preg_quote\(\)
?>

Output:

preg_quote\(\)

Example 2:

<?php
$subject = "email info@domain.com to know more.";
$replacement = "info@domain.com";
$delimiter = "@";
$pattern = preg_quote($replacement, $delimiter);
$return_value = preg_replace ("/".$pattern."/",
                     "<span style='color:red'>".$replacement."</span>", $subject);
echo $return_value;
?>

Output:

email info@domain.com to know more.

Example 3:

<?php
$subject = "preg_quote() is a built-in function. preg_quote() is used to escape special characters.";
$replacement = "preg_quote()";
$pattern = preg_quote($replacement);
$return_value = preg_replace ("/".$pattern."/",
                     "<span style='color:red'>".$replacement."</span>", $subject);
echo $return_value;
?>

Output:

preg_quote() is a built-in function. preg_quote() is used to escape special characters.

Example 4:

<?php
$subject = "preg_quote() is a built-in function. preg_quote() is used to escape special characters.";
$replacement = "preg_quote()";
$return_value = preg_replace ("/".$pattern."/",
                     "<span style='color:red'>".$replacement."</span>", $subject);
echo $return_value;
?>

Output:

preg_quote() is a built-in function. preg_quote() is used to escape special characters.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP preg_quote() Function

preg_quote() function takes a string and by adding a backslash in front of a special character, the function escapes that character and return you the same string. It is a built-in PHP pcre function.

Reference:

https://www.php.net/manual/en/function.preg-quote.php