1

A book I'm reading has this code but cant understand why so many backslashes in preg_match. The first \ might mean to match literal backslash but why two more in the expression?

This is code to "provide namespace support" with autoload:

// listing 05.18
$namespaces = function ($path) {
    if (preg_match('/\\\\/', $path)) {
        $path = str_replace('\\', DIRECTORY_SEPARATOR, $path);
    }
    if (file_exists("{$path}.php")) {
        require_once("{$path}.php");
    }
};
\spl_autoload_register($namespaces);
$obj = new util\LocalPath();
$obj->wave();

2 Answers2

0

PHP (like many languages) requires backslashes to be escaped with backslashes. Regular expressions also require backslashes to be escaped with backslashes. Thus, to match a single literal backslash, in a regular expression string, you must use \\\\: PHP converts the string into two escaped backslashes, which the regular expression parser sees as one escaped backslash.

Adrian
  • 42,911
  • 6
  • 107
  • 99
0
  1. I want to match: \
  2. So I need the regex: /\\/
  3. It needs to be represented in PHP by a string, so that looks like: '/\\\\/'.
Sammitch
  • 30,782
  • 7
  • 50
  • 77