繁体   English   中英

php regex用单个替换双反斜杠

[英]php regex replace double backslash with single

我不想使用stripslashes()因为我只想用“\\”替换“\\\\”。

我试过preg_replace("/\\\\\\\\/", "\\\\", '2\\\\sin(\\\\pi s)\\\\Gamma(s)\\\\zeta(s) = i\\\\oint_C \\\\frac{-x^{s-1}}{e^x -1} \\\\mathrm{d}x');

我的失望归咎于: 2\\\\sin(\\\\pi s)\\\\Gamma(s)\\\\zeta(s) = i\\\\oint_C \\\\frac{-x^{s-1}}{e^x -1} \\\\mathrm{d}x

各种在线正则表达式测试人员表明上述应该有效。 为什么不呢?

首先,正如许多其他人所说的那样,正则表达式对于工作而言可能过于沉重,但是您使用的解决方案应该可行。

$newstr = preg_replace('/\\\\/', '\\', $mystr);

将给出预期的结果,请注意preg_replace返回一个新的字符串,并不会修改现有的字符串,这可能是你要挂起的。

在这种情况下,您还可以使用较便宜的str_replace:

$newstr = str_replace('\\\\', '\\', $mystr);

这种方法花费的CPU时间和内存要少得多,因为它不需要为这样的简单任务编译正则表达式。

你不需要使用正则表达式,使用

$newstr = str_replace("\\\\", "\\", $mystr);

请参阅str_replace文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM