user1618054
user1618054

Reputation:

Retrieve HTML from MySQL and display in textarea

What I want to do is take HTML code stored in a MySQL table and display the raw code in a textarea. Unfortunately, the stored HTML messes up the page HTML. The reason I haven't resorted to methods like strip_tags and htmlentities is because I need the actual tags and symbols printed. The data in question contains bb code, which may look like this:

[pre]
<!--HTML CODE GOES HERE-->
[/pre]

I have a class that conveniently converts bb tags to actual html codes, which works stupendously when displaying directly on page. Once the [pre] tags are converted to <pre> tags, displaying code is not an issue. The problem occurs when displaying this data in an input/textarea element like so:

<textarea>
[pre]
<form></form>
[/pre]
</textarea>

If I try to use htmlentities, all my tags will be html codes, making editing harder and less intuitive for the user. I imagine the result would look something like this:

<textarea>
&#91;pre&#93;
...
&#91;&#47;pre&#93;
</textarea>

Given this algorithm:

  1. Get data from user

  2. Store in MySQL using prepared statement (PDO approach)

  3. Retrieve data to display whereever

  4. Sanitize this output somehow so that the result looks like this:

    < textarea > [pre] < form >< /form > [/pre] < /textarea >

Is it possible?

UPDATE:

Using a content-editable div is exactly what I need! The only question I have in regards to this solution is how do you preserve line breaks? When the data is first created, the user types into a textarea, which, when submitted, preserves line breaks in database. Outputting this using an editable div seems to remove them, which is, again, not so intuitive for the user. Thanks!

Upvotes: 1

Views: 541

Answers (2)

Neox
Neox

Reputation: 279

$htmlcontent = preg_replace('/&#91;pre&#93;/i', '[pre];', $htmlcontent);
$htmlcontent = preg_replace('/&#91;&#47;pre&#93;/i', '[/pre];', $htmlcontent);

So frustracting, it doesn't break lines in comments :/ (I need to learn how lol, I'm new to stackoverflow)

Upvotes: 1

Neox
Neox

Reputation: 279

Why not use htmlentities + a regex to replace back all the &#91;pre&#93; and &#91;&#47;pre&#93; to their original form ?

Upvotes: 0

Related Questions