How can I escape this string or shall I say characters '"); " ' (; '") ; to be put on this html element

<img src='<?=$this->webroot;?>img/document-note.png' onmouseover="tooltip.pop(this,'<?=$finalNote;?>')" />

The $finalNote variable is equal to '"); " ' (; '") ; this value.

I tried doing this one:

$finalNote = str_replace('"','\"',$finalNote);
$finalNote = str_replace("'","\'",$finalNote);

The output has become like this:

<img ;')"="" \'\")="" (;="" \'="" \"="" );="" onmouseover="tooltip.pop(this,' \'\" src="/img/document-note.png">

My code does not make sense ( I know ^_^)

I also tried using this one:

$finalNote = htmlspecialchars($finalNote);

The output is this one:

<img onmouseover="tooltip.pop(this,' '&quot;); &quot; ' (; '&quot;) ;')" src="/img/document-note.png">

That is still wrong because when I hover the image that i have it gives me this error: enter image description here

My question is that how do I escape those values properly so that I can render those on the <img onmouseover="tooltip.pop(this,' '"); " ' (; '") ; ')" /> without those errors.

Your help will be greatly appeciated! Thanks!

有帮助吗?

解决方案

You're outputting a string into Javascript, so you first need to make sure it's valid Javascript syntax. This Javascript is then output into HTML, so you need to make sure it's proper HTML. So you're looking at two encoding steps:

htmlspecialchars(json_encode($string))

To be more exact:

htmlspecialchars(sprintf('tooltip.pop(this, %s)', json_encode($finalNote)))

This is now the properly escaped content for onmouseover="...".

其他提示

<?php

$finalNote = " '\"); \" ' (; '\") ;";

$finalNote = htmlspecialchars(addslashes($finalNote), ENT_QUOTES);

?>

<script>

var tooltip = {
    pop: function(obj, note) {
        console.log(obj);
        console.log(note);
    }
};

</script>
<img src='img/document-note.png' onmouseover="tooltip.pop(this,'<?=$finalNote;?>');" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top