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?
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.
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.
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)
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
Related
I have a search form for finding restaurants. I got it handling apostrophe's just fine for the actual search, but when they're passed as \' into Javascript for mapping it's killing my maps.
Example:
xml_searchresults.php?cityID=1&type=1&searchTerm=Sonny\'s Real Bit BBQ
For a simple fix, in PHP I'm trying to go from:
$searchTerm = "Sonny\'s Real Bit BBQ" (in the original PHP file)
Then replace the \' with [slashapostrophe]:
$searchTerm = "Sonny[slashapostrophe]s Real Bit BBQ" (to be fed to javascript)
and then replace the [slashapostrophe] back with \':
$searchTerm = "Sonny\'s Real Bit BBQ" (in the PHP generated XML map marker file)
I tried str_replace but the quotes and slashes confuse it. Thanks!
php function addslashes() to quote string with '\' and stripslashes() to remove extra '\' symbols ( to unquote quoted string)
You are looking for stripslashes(): http://php.net/manual/en/function.stripslashes.php
I have searched a lot and tried javascript replace() function and str_replace,addslashes , strip slashes as well but i am not getting the right output.
This is what im doing:
str_replace("\\","\\\\", "C:wamp\www\desi\uploads\artist\bg\9.jpg";
THe output i am getting is:
C:wampwwwÞsiuploads\A rtist\B g .jpg
Then another way i tried:
var clean= "<?php echo str_replace("\\","#",LINKCONSTANT); ?>".replace("#","\\");
Still not working any idea ?
the problem isn't solvable by using str_replace like that because the string in double quotes will have the slashes processed by PHP as escape sequences. Using str_replace like this isn't going to solve the problem of PHP (or javascript) handling string escapes - once you have got a backslash into a string it will stay there quite faithfully.
However string constants will work in single quotes as follows:
'C:wamp\www\desi\uploads\artist\bg\9.jpg'
but as pointed out elsewhere the directory separator in windows is internally handled as either "/" or "\" so just use the "/" (for api calls) and you'll be fine.
If you wish to output a string that is safe to be parsed by javascript then do:
echo "var str = ".json_encode('C:wamp\www\desi\uploads\artist\bg\9.jpg').";";
which will output in a javascript compatible way:
var str = "C:wamp\\www\\desi\\uploads\\artist\\bg\\9.jpg";
What are you going to achieve? Replace the single \ by \\?
Please note, that
"\\"
denotes a string of a single \. This is due to the fact, that \ prefixes an escape sequence in used inside of "...":
\r -> Return
\t -> Tabular
\n -> Newline
Since \ has this special meaning, you need to write \\ to denote a single \ inside of "....".
Thus, this will set $resultString to C:wamp\\www\\desi\\uploads\\artist\\bg\\9.jpg:
$sourceString = "C:wamp\www\desi\uploads\artist\bg\9.jpg";
$resultString = str_replace( "\\", "\\\\", $sourceString );
I am trying to redirect some tags to another page, passing its href as a url parameter. The code I'm using is something like this:
preg_replace(
"/<a(\s[^>]*)href=[\"\']??([^\" >]*?)[\"\']??([^>]*)>(.*)<\/a>/siU",
"<a$1href=\"".WWW."go.php?to=".urlencode("$2")."\"$3>$4</a>", $text
);
It is a modified version of the regexp found here. I use this code in this block:
$text = "<...some other tags...><a target=\"_blank\" href=\"http://www.google.com\" style=\"...\" class=\"...\">Google</a></...some other tags...>";
And it correctly gets captured, but when using urlencode("$2"), it recieves a "$2" string, and not the value stored in the preg variables (as I would). It is not limited to urlencode, but to passing this as a parameter to any other function. So I would not only want to encode this (I can always extend a little more the regexp to accept urls) but generally use variables inside methods.
Do you know any workaround to this? Thanks in advance.
this is totally normal as your are url encoding the string "$2" and then the urlencoded string is used for replacement so you end up with the same thing as writing
"<a$1href=\"".WWW."go.php?to=$2\"$3>$4</a>"
as second parameter. If you want the urlencode to be evaluated you have to use the e (for eval) flag like this:
preg_replace(
"/<a(\s[^>]*)href=[\"\']??([^\" >]*?)[\"\']??([^>]*)>(.*)<\/a>/seiU",
"'<a$1href=\"'.WWW.'go.php?to=\"'.urlencode('$2').'\"$3>$4</a>'", $text
);
another preferable solution may be to use preg_replace_callback to avoid relying on evaluating unknown strings
This is a follow up on
magento escape string for javascript
where I accepted #AlanStorm suggestion to use json_encode to escape string literals.
But I now have a new problem with this solution.
when trying to escape a URL that has /'s in it to be rendered as a string literal for JavaScript json_encode seems to add redundant \'s in front of the /'s.
Any new suggestions here?
solutions should take a string variable and return a string that would properly be evaluated to a string literal in JavaScript. (I don't care if its surrounded with single or double quotes - although I prefer single quotes. And it must also support newlines in the string.)
Thanks
some more info: how comes '/');echo
json_encode($v); ?> results in
{"a":"\/"} ?
Details can be found here http://bugs.php.net/bug.php?id=49366
work around for this issue:
str_replace('\\/', '/', $jsonEncoded);
for your issue you can do something like
$jsonDecoded = str_replace(array("\\/", "/'s"), array("/", "/\'s"), $jsonEncoded);
Hope this helps
When I check the JSON format I see that solidi are allowed to be escaped so json_encode is in fact working correctly.
(source: json.org)
The bug link posted by satrun77 even says "It's not incorrect to escape slashes."
If you're adamant to do without and (in this case) are certain to be working with a string you can use a hack like this:
echo '["', addslashes($string), '"]';
Obviously that doesn't help for more complicated structures but as luck has it, you are using Magento which is highly modifiable. Copy lib/Zend/Json/Encoder.php to app/core/local/Zend/Json/Encoder.php (which forms an override) and fix it's _encodeString method.
I'm having a lot of difficulty matching an image url with spaces.
I need to make this
http://site.com/site.com/files/images/img 2 (5).jpg
into a div like this:
.replace(/(http:\/\/([^\s]+\.(jpg|png|gif)))/ig, "<div style=\"background: url($1)\"></div>")
Here's the thread about that:
regex matching image url with spaces
Now I've decided to first make the spaces into entities so that the above regex will work.
But I'm really having a lot of difficulty doing so.
Something like this:
.replace(/http:\/\/(.*)\/([^\<\>?:;]*?) ([^\<\>?:;]*)(\.(jpe?g|png|gif))/ig, "http://$1/$2%20$3$4")
Replaces one space, but all the rest are still spaces.
I need to write a regex that says, make all spaces between http:// and an image extension (png|jpg|gif) into %20.
At this point, frankly not sure if it's even possible. Any help is appreciated, thanks.
Trying Paolo's escape:
.escape(/http:\/\/(.*)\/([^\<\>?:;]*?) ([^\<\>?:;]*)(\.(jpe?g|png|gif))/)
Another way I can do this is to escape serverside in PHP, and in PHP I can directly mess with the file name without having to match it in regex.
But as far as I know something like htmlentities do not apply to spaces. Any hints in this direction would be great as well.
Try the escape function:
>>> escape("test you");
test%20you
If you want to control the replacement character but don't want to use a regular expression, a simple...
$destName = str_replace(' ', '-', $sourceName);
..would probably be the more efficient solution.
Lets say you have the string variable urlWithSpaces which is set to a URL which contains spaces.
Simply go:
urlWithoutSpaces = escape(urlWithSpaces);
What about urlencode() - that may do what you want.
On the JS side you should be using encodeURI(), and escape() only as a fallback. The reason to use encodeURI() is that it uses UTF-8 for encoding, while escape() uses ISO Latin. Same problems applies for decoding.
encodeURI = encodeURI || escape;
alert(encodeURI('image name.png'));