开发者

whitelist for html textarea

开发者 https://www.devze.com 2023-03-29 01:48 出处:网络
I am looking for a whitelist for a textarea that would be used for titles of books. The only characters I want to allow are alphanumeric, spaces, hyphens, und开发者_开发百科erscores, periods, and the

I am looking for a whitelist for a textarea that would be used for titles of books. The only characters I want to allow are alphanumeric, spaces, hyphens, und开发者_开发百科erscores, periods, and the <br> tag. Any other special characters should be converted to their htmlentities ideally. The page uses php, html, javascript, and jquery if that helps. Anyone have any ideas??

Example input in textarea:

<textarea>
I have this book called Sample- a Fake Book.    
</textarea>


If this has any relation to security, i.e. making sure the data is always safe for display, then this must be done server-side.

Except for the <br> tag, just HTML-encoding should do what you want.

Probably the best way would be to use htmlentities and then bring the <br>'s back:

$encoded_text = htmlentities($input_text);

// replace the encoded <br>'s with the original <br>'s
$final_text = str_replace(htmlentities("<br>"), "<br>", $encoded_text);

Another way to try to get this behavior and still use htmlentities is to replace the <br> tags with a placeholder, run through htmlentities, then replace it back. Something along the lines of:

$br_placeholder = "XX_BR_PLACEHOLDER_XX";
$text_with_placeholders = str_replace("<br>", $br_placeholder, $input_text);
$text_with_htmlentities = htmlentities($text_with_placeholders);
$final_text = str_replace($br_placeholder, "<br>", $text_with_htmlentities);


If you want to allow non-alphanumeric characters, but have them converted into htmlentities, then a whitelist isn't what you need. You can:

  • use javascript and regular expressions to replace <, > and & before submitting
  • let jQuery do the same thing using the $('<div/>').text(string).html() trick
  • convert them on the server side in your PHP code


Use an onkeyup handler on the textarea to detect when something's been entered. You then retrieve the textarea's content and check for 'illegal' characters:

<script type="text/javascript">
    function textFilter() {
       this.value = this.value.replace(/[^a-zA-Z0-9 \-_\.]/, '');
    }

</script>

<textarea onkeyup="textFilter();"></textarea>

Not sure what you mean "the tag", so this function will not handle "tags". Note that this simply removes illegal characters, and does not convert them to char entities.

0

精彩评论

暂无评论...
验证码 换一张
取 消