在php中用双反斜杠替换单个反斜杠

问题描述 投票:0回答:3

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

所以C:\Path\To\Filename.php最终会在数据库中找到C:PathToFileName.php。当我向谷歌发布这个问题时,我发现很多其他人遇到了同样的问题,但是在很多不同的情况下。人们总是提出类似的建议:

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

问题是,即使你把它放到某种循环中,你只需要用\替换第一个\\。所以它开始像\然后\\\然后\\\\\然后\\\\\\\然后\\\\\\\\\等...直到它用这个巨大的字符串填充内存缓冲区。

我对这个问题的解决方案,如果有其他人拥有它,那就是:

//$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

如果其他人有更好的解决方案,我会全力以赴。

php backslash
3个回答
1
投票

你需要在preg_replace参数中“双重转义”它们(一次用于字符串,一次用于正则表达式引擎):

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

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

0
投票

您可以使用正则表达式捕获组():

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

// outputs: \\b is a metasequence
© www.soinside.com 2019 - 2024. All rights reserved.