Data in my mysql database table has the special characters like '&'.
While using then I need to convert them to &
. I used the htmlspecialchars to convert them to HTML entities.
But few entry already has the &
and it converts them to &
I need them to use as it is without conversion.
What to do?
htmlspecialchars() Function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. Syntax: string htmlspecialchars( $string, $flags, $encoding, $double_encode )
HTML Encoding is a way of ensuring text will be accurately shown by a browser. The process of 'HTML encoding' involves replacing certain characters (such as < and >) with a particular 'escape sequence' of characters that a browser knows how to display and that don' interfere with browser rendering.
Definition and Usage. The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().
I think the best solution is to decode them first. Normal &
will remain untouched, but &
is decoded to &
.
Then encode them again to convert &
and other special chars to their encoded equivalent. The code is shorter than the explanation. :)
$text = 'Your text with &s from the database';
// Decode and re-encode the special characters.
$text = htmlspecialchars(htmlspecialchars_decode($text));
If you have other entities in there as well (like é
for é
),instead of htmlspecialchars
, you can also use htmlentities
and html_entity_decode
. The solution is the same, but you can test which one yields the best result for you.
$text = 'Your text with &s from the database';
// Decode and re-encode the special characters and other entities.
$text = htmlentities(html_entity_decode($text));
Both htmlspecialchars
and htmlentities
support the doubleencode
parameter, which is true by default but can be set to false. This should prevent double encoding too. It sounds like that solution is even cleaner, but I haven't used it, and I don't know if it has any side effects.
I prefer to store pure text in the DB.
& stays &, é stays é, etc...
Only when reading from DB to 'assemble' HTML content I use htmlspecialchars().
This way I know that what is stored can be used anywhere regardless if it's html or text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With