9951 explained code solutions for 126 technologies


php-regexHow to escape a slash when using regex in PHP?


To escape a slash when using regex in PHP, you can use the preg_quote() function. This function takes a string as an argument and returns a version of the string with all regex special characters escaped with a backslash.

For example:

$string = '$^.+*?|/';
echo preg_quote($string);

Output example

\$\^\.\+\*\?\|\/

The preg_quote() function escapes the following characters: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -.

Helpful links

Edit this code on GitHub