Escape only single quotes (leave double quotes alone) with htmlspecialchars()

无人久伴 提交于 2019-12-10 13:17:39

问题


I know there are other ways of of escaping only single quotes (such as this answer), but it appears to me that there should be a way using htmlspecialchars().

According to the manual, it should be some combination of their constants, but based on their explanations, I don't see it.

Is it possible to escape only single quotes, leaving the double quotes alone, with htmlspecialchars()?


回答1:


str_replace("'", "\\'", $string);

There.

Or, use ENT_QUOTES

htmlspecialchars($string, ENT_QUOTES);



回答2:


Here's the combination of constants you're looking for.

$escaped_string = htmlspecialchars($string, ENT_QUOTES & ~ENT_COMPAT, $encoding);

This will escape & ' < >, but leaves " alone. ENT_QUOTES & ~ENT_COMPAT is bit manipulation language meaning "both quotes, minus the 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 ever want to escape single quotes, but not double quotes? Well, the inverse of the reason you'd escape double quotes, but not single quotes: because you've got a string with lots of " double quotes and only a few ' single quotes, so you'd like to stick it in a '-delimited string.

An example:

<div data-myobject='<?= htmlspecialchars(json_encode($myobject), ENT_QUOTES & ~ENT_COMPAT, 'UTF-8') ?>'

json_encode() creates lots of double quotes, so it makes sense to stick the result in a single-quote delimited attribute, and leave the double quotes unescaped.




回答3:


Use htmlspecialchars(...)

Then str_replace(...) on a double quote



来源:https://stackoverflow.com/questions/10591027/escape-only-single-quotes-leave-double-quotes-alone-with-htmlspecialchars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!