James Glass
James Glass

Reputation: 4300

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

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()?

Upvotes: 7

Views: 13444

Answers (4)

Grilse
Grilse

Reputation: 3917

Community warning: although technically it's possible, normally you should never need it, which means that most likely you're doing something wrong. In case your goal is to output JavaScript data, then you should always use json_encode() for this purpose:

<script>var=<?= json_encode($php_var) ?></script>

In case you need to output this JavaScript data into HTML context, wrap it additionally in a regular htmlspecialchars() call (just like any other data):

<div data-myobject="<?= htmlspecialchars(json_encode($php_var)) ?>">

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.

Upvotes: 14

Shuja Ali
Shuja Ali

Reputation: 1

I was facing same problem and found solution by :

first

htmlspecialchars($string, ENT_QUOTES);

Then

htmlspecialchars_decode($string);

Upvotes: -1

Norse
Norse

Reputation: 5757

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

There.

Or, use ENT_QUOTES

htmlspecialchars($string, ENT_QUOTES);

Upvotes: 10

Cole Tobin
Cole Tobin

Reputation: 9425

Use htmlspecialchars(...)

Then str_replace(...) on a double quote

Upvotes: 0

Related Questions