+

Function to avoid regex patterns before applying in PHP

Syntax:
string preg_quote (string $str, string $delimiter = NULL)
Parameters :
  • $str:This parameter contains the input string.
  • $delimiter:This is an optional parameter. The most common delimiter is ` / ` because it is not a special regex character that is usually handled by the preg_quote() function. Mostly used in conjunction with the preg_replace() function .
Returns: returns a delimiter containing a string.The following program illustrates the preg_quote() function.Program 1:  
/ / Create the string to be escaped $str = " Welcome to GfG! (+ The course fee. $400) / " ; echo " Before Processing - " . $str . PHP_EOL;  
// Use preg_quote() in the above line $processedStr = preg_quote ( $str );  
// Show output echo "After Processing -" . $processedStr ;  
?>
Exit:
Before Processing - Welcome to GfG! (+ The course fee. $400) / After Processing - Welcome to GfG! (+ The course fee. $400) /
Note that every special character is preceded by a backslash, but not for a forward slash. For this we can use a separator, see the Program below:Program 2  
// Create a string to be escaped $str = "Welcome to GfG! (+ The course fee . $400) / " ; echo " Before Processing - " . $str . PHP_EOL;  
// Use preg_quote() in the above line $processedString = preg_quote ( $str , `/` );  
// Show output echo "After Processing -" . $processedString ;  
?>
Exit:
Before Processing - Welcome to GfG! (+ The course fee. $400) / After Processing - Welcome to GfG! (+ The course fee. $400) /
The program below demonstrates the combination of the functions preg_quote()and preg_replace() .Program 3:  
// PHP program highlights the word inside * * and
// use font style for italics in [] using
// both functions preg_quote() and preg_replace() $str = " The * article * was written by [GFG] " ;  
// Words to format $word1 = "* article *" ; $word2 = "[GFG] " ;  
// The first line is only applied in bold to word 1,
// preg_quote() escapes * * $processedStr1 = preg_replace ( "/" . preg_quote ( $word1 , `/` ) . "/" , " < strong > " . $word1 . "< / strong >" , $str ); echo " BOLD ONLY - " . $processedStr1 . PHP_EOL;  
// The second line applies only italics // word 2, preg_quote() escapes [] $processedStr2 = preg_replace ( " / " . preg_quote ( $word2 , `/` ) . "/" , "< em >" . $word2 . "< / em >" , $str ); echo " ITALIC ONLY - " . $processedStr2 . PHP_EOL;  
// Combine both text formatting and display $bothReplacementsCombined = preg_replace ( "/" . preg_quote ( $word2 , `/` ). "/" , "< em >" . $word2 . "< / em >" , $processedStr1 ); echo " BOTH COMBINED - " . $bothReplacementsCombined ;  
?>
Exit:
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 text formatting tags being applied, you must run PHP on your local server and navigate to a browser.
Get Solution for free from DataCamp guru