I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?
<script type="text/javascript">
$('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():
echo addslashes($value);
str_replace("'", "\'", $mystringWithSingleQuotes);
In some cases, I just convert it into ENTITIES:
// i.e., $x= ABC\DEFGH'IJKL
$x = str_ireplace("'", "'", $x);
$x = str_ireplace("\\", "\", $x);
$x = str_ireplace('"', """, $x);
On the HTML page, the visual output is the same:
ABC\DEFGH'IJKL
However, it is sanitized in source.
Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
The output would be like this:
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
Read more in PHP htmlspecialchars() Function
To replace only single quotes, use this simple statement:
$string = str_replace("'", "\\'", $string);
You can use the addcslashes function to get this done like so:
echo addcslashes($text, "'\\");
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
a PHP line created to call a JavaScript function like
echo
'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
Here is how I did it. Silly, but simple.
$singlequote = "'";
$picturefile = getProductPicture($id);
echo showPicture('.$singlequote.$picturefile.$singlequote.');
I was working on outputting HTML that called JavaScript code to show a picture...
I am not sure what exactly you are doing with your data, but you could always try:
$string = str_replace("'", "%27", $string);
I use this whenever strings are sent to a database for storage.
%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.
To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.
Happy injection avoiding!
Related
Background..
This is user input being collected so I need to expect some strange stuff and try to fix up string before passing these into functions. User input is stored into the database similar to so:
{"value":"O'Neil,'Smith',\"O'Reilly\",100"}
So the script pulls these out of the database, json_decodes them, and then now I'm trying to fix those value strings up. Here's the best example of that I can give.
$json = '{"value":"O\'Neil,\'Smith\',\"O\'Reilly\",100"}';
$array = json_decode($json, true);
The Goal..
How could I go about escaping quotes in strings like so:
O'Neil,Smith,O'Reilly,100
"O'Neil","Smith","O'Reilly",100
'O'Neil','Smith','O'Reilly',100
O'Neil,'Smith',"O'Reilly",100
So that I get the following result out of each:
'O\'Neil','Smith','O\'Reilly',100
Values may or may not contain commas. It could just be a single value like O'Neil or 100.
I'm pretty sure preg_replace could so something like this, or even preg_replace_callback, but I'm just not sure how to go about this.
The below do not work at all but I'm thinking one of these approaches should work.
$value = preg_replace('/(.*?)/', '$1', $array['value']);
$value = preg_replace_callback('/(.*?)/', 'addslashes', $array['value']);
I've also tried exploding the strings using the commas and looping the values but that escapes the quotes I don't want to touch as well.
Thanks all!
I think this function will do what you want. It uses preg_match_all to find either a quoted string (single or double, possibly with escaped quotes inside), or a set of non-comma characters. Each of those values is then trimmed of quotes, and any non-escaped single quotes are replaced with escaped ones. Finally non-numeric values are placed into single quotes:
function quote($value) {
preg_match_all('/"(?:\\\\"|[^"])*"|\'(?:\\\\\'|[^\'])*\'|[^,]+/', $value, $values);
foreach ($values[0] as &$value) {
$value = trim($value, "'\"");
$value = preg_replace("/(?<!\\\\)'/", "\\'", $value);
if (!is_numeric($value)) $value = "'$value'";
}
return implode(',', $values[0]);
}
To use with your sample strings:
echo quote("O'Neil,Smith,O'Reilly,100") . PHP_EOL;
echo quote("\"O'Neil\",\"Smith\",\"O'Reilly\",100") . PHP_EOL;
echo quote("'O\'Neil','Smith','O\'Reilly',100") . PHP_EOL;
echo quote("O'Neil,'Smith',\"O'Reilly\",100") . PHP_EOL;
Output:
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
'O\'Neil','Smith','O\'Reilly',100
Demo on 3v4l.org
I have a problem with rtrim() function in php. I have string like this one:
$str = "<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],";
Like this, embed the string in array.
I want to remove that last comma in this string. rtrim not working.
When i remove that html elements from that string, rtrim() works perfectly. anyone help?
you have to change your string like this, then it will work, it does not work because your string is inappropriate:
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of
Collateral</a> [2017-04-01],";
echo rtrim($str,",");
output is:
Picture of Collateral [2017-04-01]
The only difference is that double quoted strings interpret embedded variables and a number of escape sequences, while single quoted strings do not. E.g.:
Reference: When should you use single or double quotes in PHP?
write your code below it works
you have write string ""(double quote) and under string you also used "" string instead of this you use ''(single quote);
<?php
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of Collateral</a> [2017-04-01],";
echo rtrim($str,",");
i believe you quoted the string wrong.
try the below:
$str = rtrim('<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],',',');
echo $str;
$varHi I know this is an extremely basic task, but I am some what confused.
I am pulling a String back from a Database and assigning it to $var. I am then outputting this value into a text area. However, when I do, the string is surrounded in " ".
e.g. "This is the String", but I just want : This is the String
I have tried many functions. I am using chr(34) to search for the ", but to no avail. It will only replace them if it is inside the string. Not on the outside / surrounding the string.
$var = str_replace( chr(34), "" ,$var);
Thanks In Advance for any help.
EDIT : Turn's out I was outputting incorrectly into the text area
""
should have been
Thank's for the help.
$var = str_replace( '"', '' ,$var);
See it in action here
$var = str_replace('"', '', $var);
What about $var = str_replace('"', '', $var);?
you could use str_replace, as already mentioned but that would remove quotes from the string body also (if you have any)
to remove only the first and last ones you could use the trim function with the optional second parameter
edit: and if you have quotes inside the string that you want to keep those might be escaped so you might use str_replace to use only the quotes instead the escaped quotes ( str_replace('\"', '"', $string) );
The double speech should only appear if they are in your data being pulled, unless you are echoing or printing to the text area incorectly.
As said above the
$var = str_replace('"', '', $var);
Will work fine, but its a bit of a hack if your data doesn't have the double speech in it to start with.
I am trying to do some PHP programming concepts and I am not aware of some in-build functions. So my doubt is:
In PHP, how to remove slashes from strings? Is there any function available in PHP for this??
e.g.
$string="people are using Iphone/'s instead of Android phone/'s";
You can do a number of things here, but the two approaches I would choose from are:
Use str_replace():
$string = "people are using Iphone/'s instead of Android phone/'s";
$result = str_replace('/','',$string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
If the slashes are backward slashes (as they probably are), you can use stripslashes():
$string = "people are using Iphone\\'s instead of Android phone\\'s";
$result = stripslashes($string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
backslashes need escaping
$newstr = "<h1>Hello \ fred</h1>";
echo str_replace('\\','',$newstr);
If it is a quoted string. Use stripslashes
Heres what I use
function removeSlashes($string = '')
{
return stripslashes(str_replace('/', '', $string));
}
Test
echo $this->removeSlashes('asdasd/asd/asd//as/d/asdzfdzdzd\\hd\h\d\h\dw');
Output
asdasdasdasdasdasdzfdzdzdhdhdhdw
you can use function like
$string = preg_replace ("~/~", "", $string);
Use varian preg
$string="people are using Iphone/'s instead of Android phone/'s";
echo $string = preg_replace('/\//', '', $string);
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/uIBINP" ></iframe>
I tried this method to remove single forward slashes.
I used str_replace to strip the slashes out. It still did not work for me, I had to go and change all the double quotes in the database to single quotes, update the table, then change it back to double quotes for it to work. Weird.
str_replace('\\', '', $content)
You can use stripslashes() function.
<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>
I saved some data in the database using mysql_real_escape_string() so the single quotes are escaped like this '. It looks ok in the browser, but how can I convert it back to single quote when I save the text in a txt file?
Please note that mysql_real_escape_string() does not turn apostrophes ' into ' Only HTML-oriented functions do, so you must have calls to htmlentities() somewhere in your script.
As for your question, the function you're looking for is html_entity_decode()
echo html_entity_decode(''', ENT_QUOTES);
This is the reason why you should not store encoded text in the database. You should have stored it in it's original format, and encoded it when you display it.
Now you have to check what characters the function does encode, and write string replacements that converts them back, in reverse order.
Pseudo-code example:
s = Replace(s, "'", "'")
s = Replace(s, "<", "<")
s = Replace(s, ">", ">")
s = Replace(s, "&", "&")
That is just an ascii value of "'", use chr to get it back to a character. Here's the code
$string = "Hello ' Man";
$string = preg_replace('|&#(\d{1,3});|e', 'chr(\1)', $string);
echo $string; # Hello ' Man