Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addslashes() for preg_replace() and co.?

Tags:

regex

php

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?

like image 745
Pekka Avatar asked Dec 17 '09 11:12

Pekka


1 Answers

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: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

like image 200
Pascal MARTIN Avatar answered Sep 25 '22 01:09

Pascal MARTIN