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,846
  • 7
  • 34
  • 51
Helder Lucas
  • 3,273
  • 2
  • 21
  • 26

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
  • 761,203
  • 64
  • 569
  • 643