开发者

How can I check if the value of a textarea has HTML in it using PHP?

I am currently using jQuery to check if the textarea has HTML in it: (and I will continue to use this)

   if ($('textarea#newMessage').val().match(/<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/)) {
      $('textarea#newMessage').focus();
      $('#error').html('Error: HTML is not aloud. Please remove all of the HTML in your mes开发者_开发技巧sage to continue.')
      .click(function() { $('#newMessage').focus(); })
      .stop(true,true)
      .fadeIn(800)
      .delay(1500)
      .fadeOut(200);
      return false;
   }

But, how can I use PHP to do this same thing? If someone disables JavaScript, they can easily submit the form with HTML in it. Is there a way for PHP to do this also?


if ($text != strip_tags($text))
    // text contains html

see strip_tags


This will catch tags and no text.

$textareaname = (isset($_POST['textareaname']))
                ? $_POST['textareaname']
                : '';

if ($textareaname !== strip_tags($_POST['textareaname']))
{
    // contains tags
}

elseif (trim($textareaname ) === '')
{
    // textarea is empty
}

else
{
    // OK! do something
}

Notes:

  1. If the form is sent without anything in the textarea, $_POST['textareaname'] won't exist and PHP will throw an error when you try to use it.
  2. If someone sends nothing but spaces trim() will catch it.


Use preg_match() with the regular expression you already got. And by the way: Instead of "aloud" you probably mean "allowed" ;)


First of all, you may use exactly same regexp via preg_match

Besides, you want to restrict HTML to avoid changing anything in your code structure.
So, you may just use htmlspecialchars to print HTML as plain text.
But If you really need check, are they exists, you may just check symbols < and > that can break you markup by preg_match('~[<>]~',..) or just to strpos'es


Try this:

if(preg_match("/<[^>]*>/", $_POST['textareaname'])){
   //contains html tags
} else {
   //dosomething...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜