Function to escape regex patterns before applied in PHP
Last Updated :
31 Oct, 2019
Use preg_quote() function in PHP to escape regex patterns before it is applied in run time. The preg_quote() function puts a backslash in front of every character within the specified string that would be a part of the regex syntax in PHP, thereby making them escape sequences. These characters include:
. \ + * ? [ ^ ] $ ( ) { } = ! | : – #
Syntax:
string preg_quote( string $str, string $delimiter = NULL )
Parameters:
- $str: This parameter holds the input string.
- $delimiter: It is optional parameter. The most common delimiter is ‘/’ as it is not a special regex character that would be normally handled by preg_quote(). Primarily used in conjunction with preg_replace() function.
Returns: It returns the delimiter containing string.
Below programs illustrates the preg_quote() function.
Program 1:
<?php
$str = "Welcome to GfG! (+ The course fee. $400) /" ;
echo "Before Processing - " . $str . PHP_EOL;
$processedStr = preg_quote( $str );
echo "After Processing - " . $processedStr ;
?>
|
Output:
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. For that, we can use the delimiter, see the program below:
Program 2
<?php
$str = "Welcome to GfG! (+ The course fee. $400) /" ;
echo "Before Processing - " . $str . PHP_EOL;
$processedString = preg_quote( $str , '/' );
echo "After Processing - " . $processedString ;
?>
|
Output:
Before Processing - Welcome to GfG! (+ The course fee. $400) /
After Processing - Welcome to GfG\! \(\+ The course fee\. \$400\) \/
Below program demonstrates the combined use of preg_quote() and preg_replace() function.
Program 3:
<?php
$str = "The *article* was written by [GFG]" ;
$word1 = "*article*" ;
$word2 = "[GFG]" ;
$processedStr1 = preg_replace( "/" . preg_quote( $word1 , '/' )
. "/" , "<strong>" . $word1 . "</strong>" , $str );
echo "BOLD ONLY - " . $processedStr1 . PHP_EOL;
$processedStr2 = preg_replace( "/" . preg_quote( $word2 , '/' )
. "/" , "<em>" . $word2 . "</em>" , $str );
echo "ITALIC ONLY - " . $processedStr2 . PHP_EOL;
$bothReplacementsCombined = preg_replace( "/" .
preg_quote( $word2 , '/' ) . "/" ,
"<em>" . $word2 . "</em>" , $processedStr1 );
echo "BOTH COMBINED - " . $bothReplacementsCombined ;
?>
|
Output:
BOLD ONLY - The *article* was written by [GFG]
ITALIC ONLY - The *article* was written by [GFG]
BOTH COMBINED - The *article* was written by [GFG]
Note: To notice the application of the text formatting tags, you should run PHP on your local server and echo to the browser.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...