Preg_split with backslash

In my PHP code, I have a class name with a namespace assigned on a string like:

$my_class_name; // = "Aaa\Bbb\Ccc"; // this is not in source code, just var dump

      

I only need the middle name, "Bbb" in my case. I tried using this:

$result_array = preg_split("/\\/", $my_class_name);

      

However, this will not work. I need to use triple backslash in the regexp "/\\\/"

for it to work. My question is: why do I need three of them? I've always avoided the special backslash function by doubling it.

+3


source to share


4 answers


You want to have a literal backslash in your regex, so you must avoid it. But then you also want to put it in a PHP string , which means that you have to escape from it again.

The sequence is \\\/

broken down into

  • \\

    (one literal backslash) and
  • \/

    (a backslash followed by a slash, according to PHP string escaping rules, which is not a valid escape sequence and is therefore recognized as a pair or character character \/

    )


Four backslashes will also be translated to two backslashes, so specifying the pattern as a string literal is "/\\\\/"

equivalent to specifying it as "/\\\/"

.

But why are you using preg_split

instead explode('\\', $my_class_name)

?

+12


source


A bit weird, but you have to avoid screens as the regex gets parsed twice ...

try:



$result_array = preg_split("/\\\\/", $my_class_name);

      

+1


source


$str = "aa\\bb\\cc";
print_r(preg_split("/\\\\/", $str));

      

outputs:

Array
(
    [0] => aa
    [1] => bb
    [2] => cc
)

      

+1


source


I think this is because you need to escape once for the string and one for the regex engine

0


source







All Articles