phpregexdynamicescapingpreg-match

How escape characters in a variable to be used in a regex pattern?


I'm trying to match the following:

rawurl="http://www.example.com/page/etc/"

The URL itself is a dynamic variable and could contain all sorts (querystrings and more).

Is there an escape function to make it regex safe?

So I have this:

// $var is already defined..
$url = "www.example.com/with/extras/"
$url = str_replace(" \/ ","/",$url);  // maybe more needed here. 
$pattern = "/rawurl\=\"http\:\/\/$url/";                
preg_match($pattern, $var, $out);

I'm having problems formatting the regex correctly.


Solution

  • Take a look at preg_quote