I am writing HTML code inside PHP tags. Already for anchor tag styling is written and if I change some parts will affect. So I am trying to write my code inside the span onclick event. Here is my code
<div>
<span style='cursor:pointer;' onclick='window.location.href='www.google.com'>
".$array1[$i] ['name']."
</span>
</div>
If that array[name] is clicked, it should go to google.com. The problem is the single quotes I used for mentioning my URL. How do I escape strings in this event?
$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.
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: 1
echo '$i';
// output: $i
Keep this in mind when writing codes.
Why are you using single quotes in the first place?
<div>
<span style="cursor:pointer;" onclick="window.location.href='www.google.com'">
<?php echo $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>
<span style="cursor:pointer;" onclick="window.location.href='www.google.com'">
<?php echo $array1[$i]['name'] ?>
</span>
</div>
EOD;
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