PHP quotemeta() Function: Syntax, Usage, and Replacement with preg_quote()
The article explains PHP's quotemeta() function, which escapes special regex characters in a string, details its syntax and parameters, lists the characters it escapes, notes its deprecation after PHP 5.3, and recommends using the newer preg_quote() function with example code.
quotemeta() Function Syntax
<code>string quotemeta(string $str)</code>Parameter Description
$str : required, the string to be escaped.
Return Value
Returns the escaped string.
Function Description
The quotemeta() function escapes special characters in the given string so they are treated as literal characters in a regular expression. The characters escaped are: . , * , + , ? , [ , ^ , $ , ( , ) , { , } , | , \ , and / .
Notes
The quotemeta() function was deprecated after PHP 5.3.0 and removed in PHP 7.0.0. It is recommended to use the preg_quote() function instead.
Usage Example
<code><?php
$str = "Hello.* World+?";
echo quotemeta($str); // Output: Hello\.\*\ World\+\?
?>
</code>In this example, the string "Hello.* World+?" is passed to quotemeta() , which escapes the characters . , * , + , and ? , producing "Hello\.\*\ World\+\?".
preg_quote() Alternative
Since quotemeta() is deprecated, the preg_quote() function is recommended as a replacement. preg_quote() can escape the same characters as quotemeta() and also additional regex special characters.
Example Using preg_quote()
<code><?php
$str = "Hello.* World+?";
echo preg_quote($str); // Output: Hello\.\*\ World\+\?
?>
</code>This example shows that preg_quote() produces the same escaped result as quotemeta() for the given string.
Summary
The PHP quotemeta() function is used to escape special characters in a string for regular expressions, but it has been deprecated and removed; therefore, the preg_quote() function is recommended as a more comprehensive alternative.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.