Replacing single backslashes with double backslashes in php

人盡茶涼 提交于 2019-11-29 12:58:33
Paul Allen

You need to "double escape" them inside preg_replace parameters (once for the string, once for the regex engine):

$mystring = 'c:\windows\system32\drivers\etc\hosts';
$escaped = preg_replace('/\\\\/','\\\\\\\\',$mystring);

echo "New string is:  $escaped\n";

Or only once if you use str_replace:

 $newstring = str_replace('\\','\\\\',$mystring);

 echo "str_replace : $newstring\n";
?>
mysql_real_escape_string('C:\Path\To\Filename.php');

You can use regex capture group ():

echo preg_replace('/([\\\])/', '${1}${1}', "\b is a metasequence");
// 3 backslahses

// outputs: \\b is a metasequence
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!