Using Single Quotes (escaping) In Php
Solution 1:
I think you already got the code. However a bit more explanation:
(i) There are two types of quotes i.e. single quotes (' ... ') and double quotes (" ... "). Now when you are using one style of quote as outer quote, you can use the other style of quote inside that and you don't need to escape any quote.
e.g. echo 'He said "What a lovely day"'; output: He said "What a lovely day"
echo"She said 'that is true'";
output: She said 'that is true'
(ii) However in the second case if you wanted to output -> She said 'that's true' You need to escape the quote. In php default escape character is \
As you have already noted the quotes have special meaning to PHP. To remove the special meaning we 'escape' the character.
So you need to write: echo 'She said "that\'s true"';
or
echo "She said \"that's true\"";
This the basic concept behind escaping. But please note that the two types of quotes have different meaning in some cases. A double quote executes in the content inside them whereas a single quote assumes that the content inside them is not to be evaluated.
i.e.
$i = 1;
echo"$i";
// output: 1echo'$i';
// output: $i
Keep this in mind when writing codes.
Solution 2:
$strLocation = 'http://www.google.com';
$strLink = "<span onclick='window.location.href='".$strLocation."''>HI there</span>";
(or)
$strLink = '<span onclick="window.location.href=\''.$strLocation.'\'">HI there</span>';
print$strLink;
Using '
is an HTML special character which remains undetected during string operations and will appear only in the browser.
Using \
simply escapes the string.
Solution 3:
Why are you using single quotes in the first place?
<div><spanstyle="cursor:pointer;"onclick="window.location.href='www.google.com'"><?phpecho$array1[$i]['name'] ?></span></div>
That's all you need; there's no need to complicate things more than that :)
Per you comment, you're using this inside an echo
. I think that's a bit silly, but in that case, use heredoc
syntax
echo <<<EOD
<div><spanstyle="cursor:pointer;"onclick="window.location.href='www.google.com'"><?phpecho$array1[$i]['name'] ?></span></div>
EOD;
Solution 4:
Use json_encode
and it will reliably manage the escaping for you.
<?$exampleA = "Escape this 's"; ?><?$exampleB = 'Escape this "s'; ?><script>var a = <?= json_encode($exampleA) ?>// result: var a = "Escape this 's"var b = <?= json_encode($exampleB) ?>// result: var b = "Escape this \"s"</script>
Found here: https://stackoverflow.com/a/6269254/922522
Post a Comment for "Using Single Quotes (escaping) In Php"