1

I have looked at the documentation that PHP provides on PCRE Patterns. I am using a third party plugin to handle some text from the user, and the following preg_replace is failing because of missing terminating ] char. (preg_replace(): Compilation failed: missing terminating ] for character class

$input  = preg_replace('/[\]/i','',$userInput);

From what I can see the terminating delimiter is / with a character class that only has a \ in it. The i, if I can read correctly tells the expression to not care about upper or lower case. I see both opening [ and closing ].

Why is it throwing the error? What is the preg_replace trying to do?

3
  • To match a backslash use \\\\ ! Commented Mar 29, 2013 at 19:01
  • 1
    @Ham: \\\ is what you want. Commented Mar 29, 2013 at 19:04
  • @webbiedave Ah yes, that will also work :P Commented Mar 29, 2013 at 19:05

1 Answer 1

3

You need to escape the \ otherwise it escapes the ] (and you need to escape it twice, once for the PHP string and once for PCRE).

$input  = preg_replace('/[\\\]/i','',$userInput);

And you can omit the [ and ] altogether (as well as the i).

$input  = preg_replace('/\\\/','',$userInput);

Or, you can just use str_replace:

$input  = str_replace('\\','',$userInput);
Sign up to request clarification or add additional context in comments.

3 Comments

So you are telling me that whole thing was to replace \\ with blanks. I don't know why the script would do that, but re-write it I shall. Thanks!
I'm assuming it's a very poor attempt at escaping for an SQL query, but not know what library you're using I can only speculate.
As a rule it is better to use four backslashes to match a backslash in PHP. Although it does not apply in this case, if another backslashed character was following the three backslashes, the pattern may not be interpreted as intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.