htmlspecialchars
is for escaping characters in the main part of the HTML. For example, <
, >
and &
are special characters in HTML. They can be escaped as <
, >
and &
, respectively.
But the double-quotes for an attribute are a completely different environment. <>&
are not special characters. The only special character is "
. See https://www.w3.org/TR/html-markup/syntax.html#syntax-attributes . Actually I hadn't realised until now that you can't escape double-quotes, but that's what the spec says. So if you want to do it properly you'll have to escape them yourself, using an encoding of your choice, then unescape them when you read the attribute.
We can't use \"
for "
, because "
isn't allowed at all. Let's encode "
as %q
. Then %
is a special character, so let's encode it as %p
. Your line of PHP then becomes:
$myEscapedHTMLdescription = str_replace(array('%', '"'), array('%p', '%q'), $myHTMLdescription);
echo '<li data-desc="'. $myEscapedHTMLdescription .'" class="myTerm">'. stripslashes($myItem) .'</li>';
See http://php.net/manual/en/function.str-replace.php . Then in the javascript you have to decode it:
var description = $(this).attr('data-desc')
.replace(/%q/g, '"')
.replace(/%p/g, '%');
This is mostly untested (I don't have PHP installed here), so there may be typos.