Nick
Nick

Reputation: 906

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.

Upvotes: 3

Views: 106

Answers (1)

codaddict
codaddict

Reputation: 454960

Take a look at preg_quote

Upvotes: 10

Related Questions