PHP: escaping reserved RegEx characters - does anyone know what is wrong with this?

I am trying to avoid regular backslash characters (don't ask - just say that I'm NOT trying to parse HTML :)) And I get something strange.

$regex_chars = array('[' , '\\' , '^', '$' , '.' , '|' , '?' , '*' , '+' , '(' , ')'); $regex_chars_escaped = array('\[ ' , '\\\\ ' , '\^ ', '\& ' , '\. ' , '\| ' , '\? ' , '\* ' , '\+ ' , '\( ' , '\)'); $escaped_string = str_replace($regex_chars,$regex_chars_escaped, implode("",$regex_chars)); echo implode('&nbsp;',$regex_chars) . "<br />"; echo $escaped_string; 

Spaces for clarity. This is the conclusion.

 [ \ ^ $ . | ? * + ( ) \\ [ \\ \^ \& \. \| \? \* \+ \( \) 

So, all is well, except for the first part. Where does "\\" come from and why is it not so "\ ["?

+4
source share
2 answers

Why not just use preg_quote ?

+21
source

I believe this is simply because you are specifying the characters in the array. Try the following:

 $regex_chars = array('\\' , '[' , '^', '$' , '.' , '|' , '?' , '*' , '+' , '(' , ')'); $regex_chars_escaped = array( '\\\\ ' ,'\[ ', '\^ ', '\& ' , '\. ' , '\| ' , '\? ' , '\* ' , '\+ ' , '\( ' , '\)'); 

And you should get the expected result. Check the "potential header" section in str_replace function function

+2
source

All Articles