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

I know there are other ways to avoid single quotes ( such as this answer ), but it seems to me that there should be a way to use htmlspecialchars () .

According to the manual, this should be some combination of their constants, but based on their explanations, I do not see this.

Is it possible to avoid single quotes by leaving only double quotes with htmlspecialchars() ?

+6
source share
3 answers
 str_replace("'", "\\'", $string); 

There.

Or use ENT_QUOTES

 htmlspecialchars($string, ENT_QUOTES); 
+9
source

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.

+9
source

Use htmlspecialchars (...)

Then str_replace (...) in double quotes

+1
source

Source: https://habr.com/ru/post/915734/


All Articles