how to replace 'abc' to 'a\0\0c'
the following code is fail and give output 'ac'
<?php
$input = 'abc';
$pattern = '/b/i';
$replace = "\\0\\0";
$output = preg_replace($pattern, $replace, $input);
echo $output;
?>
how to replace 'abc' to 'a\0\0c'
the following code is fail and give output 'ac'
<?php
$input = 'abc';
$pattern = '/b/i';
$replace = "\\0\\0";
$output = preg_replace($pattern, $replace, $input);
echo $output;
?>
When in doubt add more backslashes:
$replace = '\\\\0\\\\0';
The first level of escaping is for the PHP string parser. Both single quotes and double quotes interpret \\
as \
. The next level is for the regex parser.
So PHP sees:
\\\\0\\\\0
which it interprets as:
\\0\\0
which the regex parser interprets as the literal string:
\0\0
here's a "neater" another way without those extra slashes
$string="abc";
$s = split("[bB]",$string);
print_r( implode('\0\0' , $s) );