Reputation: 1065
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?
Upvotes: 9
Views: 9798
Reputation: 1190
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.
Upvotes: 1
Reputation: 116110
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.
Upvotes: 7