Nathan
Nathan

Reputation: 12000

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 message 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?

Upvotes: 3

Views: 1894

Answers (5)

Herbert
Herbert

Reputation: 5778

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.

Upvotes: 2

Kakashi
Kakashi

Reputation: 2195

Try this:

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

Upvotes: 1

RiaD
RiaD

Reputation: 47620

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

Upvotes: 1

harpax
harpax

Reputation: 6106

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

see strip_tags

Upvotes: 4

str
str

Reputation: 44969

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

Upvotes: 1

Related Questions