PHP how to replace \\ with \ using preg_replace
i want to replace \\
with \
in 开发者_StackOverflow中文版PHP i tried this code but it doesn't work any idea ?
$var= preg_replace('/\\\\/', "\\", $var);
thanks a lot
Use stripcslashes() or stripslashes() instead. There is no good reason for regular expressions here and on the other hand they are more expensive than the built-in functions.
Is there a particular reason you want to use preg_replace ? You should be using str_replace :
php > echo str_replace("\\\\", "\\", "I\\\\'ve had");
I\'ve had
The problem is that with preg_replace, you have to escape the \
for PHP's interpreter AND you have to escape \
again for regexp's interpreter. So basically, you'd have to write this :
php > echo preg_replace("/\\\\\\\\/", "\\", "I\\\\'ve had");
I\'ve had
Because to write a \
in a php string, you have to write \\
, but you have to escape both for regexp's interpreter, and it becomes \\\\
. That's a single \
, so you have to repeat it twice.
精彩评论