1

I need to preg_match() a pattern in PHP and no matter what I do I get errors.

I've looked all over the net and can't find anything that tells me what I'm actually doing wrong.

Here's my preg_match pattern:

preg_match('/\MyApp\Library\Task\/', '\MyApp\Library\Task\Db\Generate');

It always returns an array, what do I do wrong? How can I get my regex to work properly?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
secondman
  • 3,233
  • 6
  • 43
  • 66
  • Shouldn't you escape the backslashes in your regular expression ? This problem has been mentioned here http://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex :) – Cr3aHal0 May 15 '15 at 07:46

1 Answers1

10

I know it will sound crazy, but you need to use 4 backslashes to get 1 backslash for your regex. So your code would look something like this:

preg_match('/\\\\MyApp\\\\Library\\\\Task\\\\/', '\MyApp\Library\Task\Db\Generate');

Why do you need to use 4? Because in PHP you use a backslash to escape the following character, so you escape it to get one literal backslash (\\).

But since we are are in a regular expression you need to escape a backslash if you want a backslash in your regex, means you have to use \\ two backslashes which with PHP end up in one to escape the other two backslashes which always end up in one character, which then end up as a single backslash in your regex.

Rizier123
  • 58,877
  • 16
  • 101
  • 156