Here is a combination of the constants you are looking for.
$escaped_string = htmlspecialchars($string, ENT_QUOTES & ~ENT_COMPAT, $encoding);
This will cause & ' < >
to disappear, but leave it alone. ENT_QUOTES & ~ENT_COMPAT
is a bit manipulation language meaning "both quotes, minus double quotes."
This works because of how these constants are defined. php-src / ext / standard / html.h
#define ENT_HTML_QUOTE_NONE 0 #define ENT_HTML_QUOTE_SINGLE 1 #define ENT_HTML_QUOTE_DOUBLE 2 #define ENT_COMPAT ENT_HTML_QUOTE_DOUBLE #define ENT_QUOTES (ENT_HTML_QUOTE_DOUBLE | ENT_HTML_QUOTE_SINGLE) #define ENT_NOQUOTES ENT_HTML_QUOTE_NONE
Why would you like to avoid single quotes, but not double quotes? Well, on the contrary, you avoid double quotes, but not single quotes: because you have a string with a lot of double quotes "
and only a few single quotes '
, so you would like to insert it in the string '
-delimited.
Example:
<div data-myobject='<?= htmlspecialchars(json_encode($myobject), ENT_QUOTES & ~ENT_COMPAT, 'UTF-8') ?>'
json_encode()
creates a lot of double quotes, so it makes sense to stick to the result in a single quote delimited attribute and leave double quotes without saving.
source share