Replacing single backslashes with double backslashes in php

自作多情 提交于 2019-11-28 06:45:55

问题


I came across a strange problem in my PHP programming. While using the backtrace function to get the last file the PHP compiler was working with. It would give it to me the path using backslashes. I wanted to store this string in the database, but MySQL would remove them; I'm assuming it was thinking I wanted to escape them.

So C:\Path\To\Filename.php would end up C:PathToFileName.php in the database. When I posted this question to Google, I found many others with the same problem but in many different situations. People always suggested something like:

$str = '\dada\dadda';
var_dump(str_replace('\', '\\', $str)); 

The problems with this is, even if you put it into a loop of some kind, is that you just keep replacing the first \ with \\. So it starts off like \ then \\\ then \\\\\ then \\\\\\\ then \\\\\\\\\ etc... Until it fills the memory buffer with this huge string.

My solution to this problem, if anyone else has it is:

//$file = C:\Path\To\Filename.php

//Need to use \\ so it ends up being \
$fileArray = explode("\\", $file);

//take the first one off the array
$file = array_shift($fileArray);

//go thru the rest of the array and add \\\\ then the next folder
foreach($fileArray as $folder){
    $file .= "\\\\" . $folder;
}

echo $file
//This will give you C:\\Path\\To\\Filename.php

So when it's stored in the database, it will appear to be C:\Path\To\Filename.php.

If anyone else has a better solution to this, I'm all ears.


回答1:


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";
?>



回答2:


mysql_real_escape_string('C:\Path\To\Filename.php');



回答3:


You can use regex capture group ():

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

// outputs: \\b is a metasequence


来源:https://stackoverflow.com/questions/15983782/replacing-single-backslashes-with-double-backslashes-in-php

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