用PHP中的双反斜杠替换单个反斜杠 [英] Replacing single backslashes with double backslashes in php

查看:966
本文介绍了用PHP中的双反斜杠替换单个反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP编程中遇到了一个奇怪的问题.使用backtrace函数获取PHP编译器正在使用的最后一个文件时.它将使用反斜杠为我提供路径.我想将此字符串存储在数据库中,但是MySQL会删除它们.我以为是我想逃避他们.

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.

因此,C:\Path\To\Filename.php将最终在数据库中成为C:PathToFileName.php.当我将此问题发布到Google时,我发现许多其他问题相同但处在不同情况下的问题.人们总是建议如下:

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

因此,当它存储在数据库中时,它将显示为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.

推荐答案

您需要在preg_replace参数中对它们进行双重转义"(一次用于字符串,一次用于regex引擎):

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

或如果使用str_replace仅一次:

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

 echo "str_replace : $newstring\n";
?>

这篇关于用PHP中的双反斜杠替换单个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆