Undefined Variable
Undefined Variable

Reputation: 4267

How to escape a set of characters in a string

So I have a variable say "$x". I have to escape a set of special characters if they show up in this string. The characters I want to escape are:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \

I am not very good with regex, but I think that is how I should do it, yeah?

I can escape them like str_replace("+","\+",$x); for each special character, but I am not sure that is how it should be done. Any pointers anyone?

Upvotes: 0

Views: 82

Answers (1)

varu
varu

Reputation: 339

You can use the function preg_quote. It 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.

Upvotes: 2

Related Questions