-1

I have the following code:

  $URI = "controller/method/parms";
  $pattern = "a-z0-9_-/";
  echo preg_match("/^[". $pattern ."]+$/i", $URI);

Because of this / symbol, the operation fails and appears this error:
Warning: preg_match(): Unknown modifier ']'. but if I remove that symbol, everything will work correctly.

Lion King
  • 32,851
  • 25
  • 81
  • 143

1 Answers1

2

Escape the slash and move the dash at the end of the character class:

$pattern = "a-z0-9_\/-";
preg_match("/^[". $pattern ."]+$/i", $URI);

Note: preg_quote doesn't work in this case because it escapes the dash, I don't know why.

You could also use another delimiter:

$pattern = "a-z0-9_/-";
preg_match("~^[". $pattern ."]+$~i", $URI);
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Unfortunately, the error message still appears, in both cases. – Lion King Mar 18 '17 at 13:11
  • @LionKing: Sorry, I missed the second parameter :) – Toto Mar 18 '17 at 13:17
  • If you `preg_quote()` the `$pattern` that contains `\w` the `\w` will get escaped and won't match. – nickb Mar 18 '17 at 13:21
  • @nickb: True, I remove it. – Toto Mar 18 '17 at 13:23
  • Thanks, the error message disappeared, but always the function returns 0, and that mean it has failed. – Lion King Mar 18 '17 at 13:29
  • @LionKing:Preg_quote escape the dash, even in the range `a-z`, that's crazy. See my edit for an alternative. – Toto Mar 18 '17 at 13:39
  • 1
    @Toto: `preg_quote` is designed to escape literal strings, not a character class content. It escapes regex special characters `. \\ ? + * ( ) { [ | ^ $` but in addition it escapes also characters that are used in special sequences: `=` => `(?=...)`, `]` => `[...]`, `}` => `{m,n}`, `-` => `(?-i)`, `>` => `(?>...)`, `:` => `(?:...)`, etc. Note that strangely it doesn't escape the `#` that is used in comment groups: `(?#...)` – Casimir et Hippolyte Mar 18 '17 at 13:55
  • 1
    @LionKing: Anyway, since the edited version answers the question, you should accept it. – Casimir et Hippolyte Mar 18 '17 at 16:21