问题
Been struggling with replacing a backslash by another symbol such as '.-.' just to indicate the position of backslashes as I could not send a string such as 'C\xampp\etc.' through url as GET variable so I thought I'd first replace the backslashes in that string by another symbol, then send through url, and then replace them back to backslashes in the PHP file that handles it. Though would there be a better way to send such strings through url? Because when I try a script such as:
$tmp_name = preg_replace("\", ".-.", $_FILES['uploadfile']['tmp_name']);
It turns out into a php error as \ is also used as delimiter..
Could anyone help me out on this?
Thanks in advance!
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
回答1:
The regex used in preg_replace should be enclosed in a pair of delimiter and also Try using \\\
instead of \
as:
$tmp_name = preg_replace("{\\\}", ".-.", $_FILES['uploadfile']['tmp_name']);
EDIT:
To reverse the substitution you can do:
$str = preg_replace('{\.-\.}',"\\",$str);
You need to escape the .
to match a literal dot.
回答2:
use urlencode()
/urldecode()
.
echo urlencode('C:\xampp\etc'); // C%3A%5Cxampp%5Cetc
BTW: This sounds like a huge security flaw (sending absolute paths by request)
PS: preg_replace()
is for regular expressions. Try str_replace()
next time.
回答3:
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
That's easy. PHP:
$url = 'http://example.com/?array=' . urlencode(serialize($array)); // html
$array = unserialize($_GET['array']); // server side
Or Javascript:
url = "http://example.com/?array=" + encodeURIComponent(JSON.stringify(array)); // client
$array = json_decode($_GET['array']); // server
(for Javascript you'll have to look up whether encodeURIComponent is correct, and you need the official JSON library as well)
回答4:
If you're not using a regular expression (which you're not), you should use str_replace
instead:
$tmp_name = str_replace('\\', '.-.', $_FILES['...']);
Note that you have to escape the \
with another \
(otherwise it'd escape the following '
).
As for the delimiter error - regular expressions need to be enclosed in delimeters, for example /foo/
(/
is the delimiter, foo
is the pattern). But, again, there's no need for you to use or worry about regexps
来源:https://stackoverflow.com/questions/2482637/replacing-backslash-with-another-symbol-in-php