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.
source to share
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)
?
source to share