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
Related
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 have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n');";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n into the source of the page.
Can anyone point me in the right direction? Thanks.
Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.
Try this:
$str="var lines = data.split('\\n');";
you can escape \ like this: \\.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...
Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.
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 writing a php forms class with client and server side validation. I'm having problems checking if a literal backslash ("\") exists in a string using regular expressions in javascript.
I want to shy away from solutions other than using regex as this will reduce the amount of special cases between php and js AND reduce the amount of conditional code I need to write.
I've just been using this as an example of what a user may need in this forms class-
A password field that is a string
between 6 and 12 chars long and that
excludes "\","#","$","`"
I have tried:
^[^(\u0008#\$`)]{6,12}$
^[^(\b#\$`)]{6,12}$
^[^(\\#\$`)]{6,12}$
And none of them work for a backslash and I can't work out why. FYI: The latter works fine in PHP.
The regular expression \\ matches a single backslash. In JavaScript, this becomes re = /\\/ or re = new RegExp("\\\\").
ripped straight from http://www.regular-expressions.info/javascript.html
It looks like you've created a grouping of slash-hash-dollar-tick, rather than looking for any of those characters.
try this
var rgx = new RegExp(/^[^\\#\$`]{6,12}$/);
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