tags:

views:

60

answers:

3

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;
?>
A: 

Have you tried

$replace = '\\0\\0';

?

masher
output will give "abbc"not a expected value
brian
Have you tried a different `$replace` string? Is it just a problem with your wanting to insert `\0\0`, or is something drastically broken somewhere else?
masher
i have tried it, it work for other string, but i need to replace with \0\0, php give the strange output
brian
+5  A: 

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
Matthew Flaschen
+1, i was just toooo slow...Also @OP: gives the example in the php docs - http://php.net/manual/en/function.preg-replace.php
munch
thank you matthew ^^ you are great
brian
A: 

here's a "neater" another way without those extra slashes

$string="abc";
$s = split("[bB]",$string);
print_r( implode('\0\0' , $s) );
ghostdog74