1

I want to use htmlspecialchars on user's textarea, but I want him to allow to use bold and italic. How can I not use htmlspecialchars on those tags?

good_evening
  • 21,085
  • 65
  • 193
  • 298

2 Answers2

5

Use the better-safe-than-sorry method. That is you first apply htmlspecialchars, and then very selectively undo it / whitelist your two tags:

 $html = htmlspecialchars($html);
 $html = preg_replace('#&lt;(/?[bi])&gt;#', '<$1>', $html);

That works only when those tags only contain those exact two strings, no extra attributes. No safety or consistency concerns with that however (except that this short version doesn't assert balanced tags, ooops).

If you need more complex rules, then HTMLPurifier is what you should look out for.

mario
  • 144,265
  • 20
  • 237
  • 291
  • @mario: If you leave it will make bold all text below. – good_evening Dec 11 '11 at 19:06
  • Yes, you need to make it more clever then. `'#<([bi])>(.*?)</\1>#', '<$1>$2$1>', $html);` – mario Dec 11 '11 at 19:12
  • @mario: This example doesn't work... And how do you know this stuff? Maybe you could suggest any tutorials? Because it seems very useful. – good_evening Dec 11 '11 at 19:16
  • 1
    Regular expressions are sort of a programming language on their own. The [syntax list in the PHP manual](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) is okay, but http://regular-expressions.info/ is more introductory. Also check out some of the tools [Open source regexbuddy](http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world) and [online guis](http://stackoverflow.com/questions/32282/regex-testing-tools). – mario Dec 11 '11 at 19:21
-2

I like to use the tinyMCE jquery plugin for this kind of thing.

http://www.tinymce.com/tryit/jquery_plugin.php

hope that helps.

Simon
  • 375
  • 5
  • 12