Possible Duplicate:
Is there a PHP function that can escape regex patterns before they are applied?
I want to use a string stored in a variable in a regular expression. What's the best way (in PHP) to escape a string for use in a (PCRE) regular expression?
For example,
$text = 'm/z'; // this is the text I want to use as part of my regular expression $text_regexp = '#' . $text . '#i'; // this is my regular expression
Would give
$text_regexp = '#m/z#i';
But I would want the following regular expression:
$text_regexp = '#m\/z#i';
This is a contrived example, but I wanted to illustrate the point simply.
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.
To match any of the metacharacters literally, one needs to escape these characters using a backslash ( \ ) to suppress their special meaning. Similarly, ^ and $ are anchors that are also considered regex metacharacters.
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
preg_quote
From the manual:
puts a backslash in front of every character that is part of the regular expression syntax
You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using #
as your delimiter, then there's no need to escape /
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With