Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping string for use in regular expression [duplicate]

Tags:

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.

like image 385
Tomba Avatar asked Feb 08 '11 17:02

Tomba


People also ask

How do you escape a string in regex?

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.

How do you escape a double quote in regex?

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.

How do you escape a metacharacter in regex?

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.

Do you need to escape dash in regex?

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).


1 Answers

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 /

like image 75
webbiedave Avatar answered Sep 24 '22 12:09

webbiedave