2

So I'm having the following issue with regular expressions:

What I am trying to achieve: Get the last element of the namespace, in this case "BAZ"

To do so I am using the regular expression below:

preg_match("/[^\\]*$/", 'Foo\Bar\Baz', $output);

For some reason I get this error:

preg_match(): Compilation failed: missing terminating ] for character class at offset 6

chris85
  • 23,591
  • 7
  • 30
  • 47
Helder Lucas
  • 3,145
  • 1
  • 20
  • 24

1 Answers1

3

You need to double escape \\ because in PHP regex is entered as string where which requires each literal \ as \\ and regex engine needs additional escaping of each \ so you end up with 4 \:

preg_match('/[^\\\\]*$/', 'Foo\Bar\Baz', $output);
anubhava
  • 713,503
  • 59
  • 514
  • 593