trrrrrrm
trrrrrrm

Reputation: 11802

PHP how to replace \\ with \ using preg_replace

i want to replace \\ with \ in PHP i tried this code but it doesn't work any idea ?

$var= preg_replace('/\\\\/', "\\", $var);

thanks a lot

Upvotes: 0

Views: 4034

Answers (2)

Vincent Savard
Vincent Savard

Reputation: 35907

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.

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131831

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.

Upvotes: 1

Related Questions