Reputation: 458
I want to convert everything like spaces, single/double quotes, line break, etc.
Here is a sample input (Thanks som_nangia) :
Escape Check < "escape these" > <“and these”> <html><tr><td></td></tr></html> 'these will need escaping too' ‘ so will these’ <script> </script>
Here are the options I am considering:
<pre>Escape Check < "escape these" > <“and these”> <html><tr><td></td></tr></html> 'these will need escaping too' ‘ so will these’ <script> </script></pre>
/**
* Encoding html special characters, including nl2br
* @param string $original
* @return string
*/
function encode_html_sp_chars($original) {
$table = get_html_translation_table(HTML_ENTITIES);
$table[' '] = ' ';
$encoded = strtr($original, $table);
return nl2br($encoded);
}
I have tried both htmlspecialchars and htmlentities, but none of them encodes spaces.
Upvotes: 0
Views: 341
Reputation: 458
This best way is probably
Example:
function encode_html_sp_chars($original) {
$encoded = htmlentities($original, ENT_QUOTES, "UTF-8");
$encoded = str_replace(' ', ' ', $encoded);
return nl2br($encoded);
}
Upvotes: 0
Reputation: 167172
htmlspecialchars
.echo htmlspecialchars($string);
In your case, please pass two parameters this way:
echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.
If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead.
Upvotes: 5