[英]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 ? 我想在PHP中用\\
替换\\\\
我试过这段代码,但它不起作用吗?
$var= preg_replace('/\\\\/', "\\", $var);
thanks a lot 非常感谢
Use stripcslashes() or stripslashes() instead. 请改用stripcslashes()或stripslashes() 。 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 ? 您是否有特殊原因要使用preg_replace? You should be using str_replace : 你应该使用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. 问题是,与preg_replace函数,你必须逃离\\
的PHP解释器,你必须逃脱\\
再次为正则表达式的解释。 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 \\\\\\\\
. 因为要在php字符串中写一个\\
,所以必须写\\\\
,但是必须对regexp的解释器都进行转义,然后它变成\\\\\\\\
。 That's a single \\
, so you have to repeat it twice. 这是一个\\
,所以你必须重复两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.