tags:

views:

50

answers:

2

How can I escape incoming data so I can use it as a pattern in preg_replace() and consorts? For example, I need to match against this string:

/vorschau/

Obviously, I need to escape the "v" or I will get an error.

I can't find anything in the documentation. Is there some sort of addslashes() for this, or a workaround within the expression?

+3  A: 

If I understand your question correctly, you are looking for preg_quote :

string preg_quote  ( string $str  [, string $delimiter = NULL  ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax.
This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Pascal MARTIN
That's exactly what I looked for and didn't know about. Thanks!
Pekka
@Pekka : you're welcome :-) (I hate when I see code in which some one re-invented to whell and tried to re-code this function, actually ^^ )
Pascal MARTIN
A: 

It does seem that you want preg_quote, but perhaps you should detail your situation more, because it’s quite possible that what you are trying to do could be done a better way.

Ciarán Walsh
preg_quote() it is. I need to remove a base directory from the request URI: e.g. removing `/mydirectory` from `/mydirectory/xyz/123` = results in `/xyz/123`, and `preg_replace()` looks like the most elegant way to do it. If you have a better solution fire away!
Pekka
`$stripped = substr($fullpath, strlen($basedir));`
nikc
All right, you have a point! Nice one.
Pekka
Regex is great, but rarely the best solution to simple string manipulation like that :)
Ciarán Walsh