检测textarea提交中的特定单词

时间:2011-10-15 21:00:40

标签: php html forms textarea blacklist

我的网站上有一个新功能,用户可以通过textarea提交任何文本(我停止了所有HTML条目)。我仍然遇到的主要问题是他们可以键入“http://somewhere.com”,这是我想要停止的。我还想将特定单词列入黑名单。这就是我之前所拥有的:

if (strpos($entry, "http://" or ".com" or ".net" or "www." or ".org" or ".co.uk" or "https://") !== true) {
            die ('Entries cannot contain links!');

然而,这不起作用,因为它阻止用户提交任何文本。所以我的问题很简单,我该怎么做?

3 个答案:

答案 0 :(得分:2)

这是Regular Expressions的工作。

你需要做什么这样的事情:

// A list of words you don't allow
$disallowedWords = array(
  'these',
  'words',
  'are',
  'not',
  'allowed'
);
// Search for disallowed words.
// The Regex used here should e.g. match 'are', but not match 'care' or 'stare'
foreach ($disallowedWords as $word) {
  if (preg_match("/\s+$word\s+/i", $entry)) {
    die("The word '$word' is not allowed...");
  }
}

// This variable should contain a regex that will match URLs
// there are thousands out there, take your pick. I have just
// used an arbitrary one I found with Google
$urlRegex = '(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*';

// Search for URLs
if (preg_match($urlRegex, $entry)) {
  die("URLs are not allowed...");
}

答案 1 :(得分:0)

你必须多次使用strpos。用你的方式评估or语句,返回true / false并将其传递给strpos。

这样它应该有效:

if (strpos($entry, "http://") !== false || strpos($entry, "https://") !== false || strpos($entry, ".com") !== false)

答案 2 :(得分:0)

执行此操作的一种简单方法是将所有不允许的单词放入数组中并循环遍历它们以检查每个单词。

$banned = array('http://', '.com', '.net', 'www.', '.org'); // Add more
foreach ($banned as $word):
    if (strpos($entry, $word) !== false) die('Contains banned word');
endforeach;

问题在于,如果你太过分,并开始禁止使用'com'这个词,那么还有其他单词和短语可能是完全合法的,其中包含字母'com'会导致假阳性。您可以使用正则表达式来搜索看起来像URL的字符串,但是您可以轻松地像上面那样分解它们。没有有效的方法可以完全阻止人们将链接发布到评论中。如果你不想要它们,你最终只需要使用适度。社区审核工作非常顺利,例如,请查看Stack Overflow