Using UTF-8
character directly
You may use (assuming UTF-8
) directly "smiley face character", its hex sequence is 0xE2 0x98 0xBA (e298ba)
:
mysql> SELECT CHAR(0xe298ba USING UTF8);
+---------------------------+
| CHAR(0xe298ba USING UTF8) |
+---------------------------+
| ☺ |
+---------------------------+
1 row in set (0.00 sec)
I do NOT recommend doing this (but you it's possible), if you really want to store modified data in the database rather use HTML entry ☺
(which won't put any special characters into database).
UPDATE `conversations_messages`
SET message_text = REPLACE(message_text, ':)', '☺')
Of course this assumes you don't do any html filtering (like htmlspecialchars()
) after loading data from database.
But I wouldn't store modified data in the database (at least not without storing original version), imagine scenario when you would want to add new smiley face after "processing" every message you already have (or worse remove it)...
If you (for some reason) really have to replace it as a par of "model" rather use:
SELECT REPLACE(`message_text`, ':)', '☺') AS message_text
Or rather build stored function which will do multiple steps (replace newlines, smiley faces and so on).
SELECT MyProcessingFunction(`message_text`) AS message_text
Much more suitable way of doing this will be "decorating text" when it's printed out
function process_text($text)
{
$text = htmlspecialchars($text);
$text = str_replace( '\n', '<br />', $text);
$text = str_replace( ':)', '&@x263a;', $text);
return $text;
}
$message_text = do_some_magic();
echo process_text($message_text);
This way you still have original available and can change formatting on the fly without corrupting old data.
Using <img />
tag
Much more common way (at least in my experience) is using images (small images):
function process_text($text)
{
$text = htmlspecialchars($text);
$text = str_replace( '\n', '<br />', $text);
$text = str_replace( ':)', '<img class="smiley" src="..." alt=":)" />', $text);
return $text;
}
This will give you much more freedom (use your own smileys, style them a bit) when doing things.
Another tips
You can use nl2br()
instead of replacing newlines manually (but last time I've worked with it, it wasn't XHTML compatible... which it is since 4.0.5
).
Also sanitize user inputs (database input - prepared statements and parameters; output - htmlspecialchars()
or equivalent) to prevent users from XSS or just screwing up your page.
`. – Orel Eraki Feb 22 '14 at 20:57
", $messages['message_text']); gives me an error – user3315726 Feb 22 '14 at 21:02