>
> $a = "\\n";
> $from = array("\\", "\n");
> $to = array("\\\\", "\\n");
>
> // forward conversion
> $b = str_replace($from, $to, $a);
> // backwards conversion
> $c = str_replace($to, $from, $b);
>
> $c will becomes "\n", not "\\n".
>
> The reason, of course, is that str_replace does not respect escaped
> characters. It is simpler to escape \ characters by appending a dummy
> character than using a full fledged parser to perform a simple string-
> replace.

It should work if we use strtr. Try this:

<?php
$a = "he\\she just tested \ something like \n \\n \\\n \\\\n ";
echo $a;
// forward conversion
$b = strtr($a, Array("\\" => "\\\\", "\n" => "\\n"));
echo $b;
// backwards conversion
$c = strtr($b, Array("\\\\" => "\\", "\\n" => "\n"));
echo $c;

str_replace does array-to-array replacement in a 2 parts way, it means
that
$b = str_replace(Array($f1, $f2), Array($t1,$t2), $a);
does the same as:
$b = str_replace($f1, $t1, $a);
$b = str_replace($f2, $t2, $b);

while strtr does the replacement at once, so after replacing "\\\\" to
"\\" in "\\\\n", and then the next match starts at "n" so no "\\n" to
"\n" replace would happen for it.
-- 
You received this message because you are subscribed to the Google Groups 
"BoltWire" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/boltwire?hl=en.


Reply via email to