title: Formatting text from database
body: <p>I have a textarea on my page where i allow users to write text. To preserve linebreaks that users make while inputting I use:</p>
  
  <pre><code>editBox.val().replace(/\r?\n/g, "\r\n");
  </code></pre>
  
  <p>Before the data is uploaded to the database I'm using:</p>
  
  <pre><code>$data = mysql_real_escape_string($data);
  </code></pre>
  
  <p>I do this to preserve as much data as possible without stripping data that might be useful later on. This also helps me to preserve possible formatting options that can be allowed later. I read that this is good practice.</p>
  
  <p><strong>The problem is</strong>:</p>
  
  <p>When the data is pulled from the database i need to clean it. For that I'm using:</p>
  
  <pre><code>function cleanData($data) 
  {           
      $data = nl2br($data);
      $data = strip_tags($data,"&lt;br&gt;&lt;b&gt;&lt;p&gt;&lt;i&gt;&lt;h1&gt;&lt;h2&gt;&lt;h3&gt;&lt;h4&gt;&lt;h5&gt;&lt;h6&gt;");
      return $data;
  }
  </code></pre>
  
  <p>I'm allowing certain tags that will later be used with a little self-made wysiwyg editor.
  However this allows for users to input the following:</p>
  
  <pre><code>&lt;p title="some junk here"&gt;hax&lt;/p&gt;
  </code></pre>
  
  <p>While the title attribute isn't incredibly annoying, other attributes may. I'm not sure whether a user can add class and id attributes, but i can't see why they shouldn't be able to. It also removes anything that looks like a tag such as smilies: <code>"*&lt;:o) &lt;- happy clown"</code> would end up looking something like this: <code>"*"</code></p>
  
  <p>I tried using:</p>
  
  <pre><code>$data = filter_var($data, FILTER_SANITIZE_SPECIAL_CHARS);
  </code></pre>
  
  <p>Instead of the cleanData function, however this encodes everything showing my <code>&lt;br&gt;</code> converted line breaks as text instead of adding line breaks.</p>
  
  <p><br /><br /></p>
  
  <p><strong>In short my problem is:</strong></p>
  
  <p>I can't seem to find a nice way to clean the data so linebreaks/br are preserved while also retaining the possibillity to add some sort of wysiwyg formatting. I don't really care whether it's html tags or something like bbCode: <code>[b]</code>.</p>
  
  <p><br /></p>
  
  <p><strong>My question is as follows:</strong></p>
  
  <p>Is there a smarter way to do this or is my method fine with a few tweaks?</p>
  
  <p>What would you guys do? :) I would like to avoid using external libraries unless there's a very strong inscentive.</p>
  
  <p><br /></p>
  
  <p><strong>PS</strong>: I've searched around lot and found no satisfactory answer - I've also spent a long time making this post readable and understandable. I hope I've done it right.</p>