简体   繁体   English

如何使用PHP检查textarea的值是否包含HTML?

[英]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) 我目前正在使用jQuery来检查textarea中是否包含HTML :(我会继续使用它)

   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? 但是,我如何使用PHP来做同样的事情呢? If someone disables JavaScript, they can easily submit the form with HTML in it. 如果某人禁用了JavaScript,他们可以轻松地在其中提交包含HTML的表单。 Is there a way for PHP to do this also? 有没有办法让PHP也这样做?

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

see strip_tags 请参阅strip_tags

Try this: 尝试这个:

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

Use preg_match() with the regular expression you already got. 将preg_match()与您已经使用的正则表达式一起使用。 And by the way: Instead of "aloud" you probably mean "allowed" ;) 顺便说一句:你可能意味着“允许”,而不是“大声”;

First of all, you may use exactly same regexp via preg_match 首先,您可以通过preg_match使用完全相同的regexp

Besides, you want to restrict HTML to avoid changing anything in your code structure. 此外,您希望限制HTML以避免更改代码结构中的任何内容。
So, you may just use htmlspecialchars to print HTML as plain text. 因此,您可以使用htmlspecialchars将HTML作为纯文本打印。
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 但是如果你真的需要检查,它们是否存在,你可以只检查符号<> ,它们可以通过preg_match('~[<>]~',..)来破坏你的标记,或者只是为了strpos

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. 如果表单在textarea中没有任何内容发送,则$_POST['textareaname']将不存在,并且当您尝试使用它时PHP将引发错误。
  2. If someone sends nothing but spaces trim() will catch it. 如果有人只发送空格trim()将捕获它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM