Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

backslash - Replacing single backslashes with double backslashes in php

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:PathToFilename.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 = 'dadadadda';
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:PathToFilename.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:PathToFilename.php.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

$mystring = 'c:windowssystem32driversetchosts';
$escaped = preg_replace('/\\/','\\\\',$mystring);

echo "New string is:  $escaped
";

Or only once if you use str_replace:

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

 echo "str_replace : $newstring
";
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...