1

I've had a look at this question, which shows what characters need to be escaped. However, I'm having a lot of trouble constructing a regex that will match any instance of one of those characters in a string.

For some background on the problem, I'm implementing a simple word-for-word (or term-for-term if you prefer) translation database where users enter language pairs, and can then trigger translations on blocks of text. The problem comes when users enter strings like "Yes/No". So, in PHP, I need to escape the string to be matched, and place it like this:

"/\b".$target."\b/"

So, what do I need to be looking at in terms of a preg_replace?

Community
  • 1
  • 1
Fibericon
  • 5,684
  • 12
  • 37
  • 64

1 Answers1

4

You want to use preg_quote(). As the documentation clearly states:

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.

Or \Q ... \E, ( What's between \Q and \E is treated as normal characters, not regular expression characters. )

hwnd
  • 69,796
  • 4
  • 95
  • 132