0

我的网站上有一个新功能,用户可以通过 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!');

然而这并没有奏效,因为它完全阻止了用户提交任何文本。所以我的问题很简单,我该怎么做?

4

3 回答 3

2

这是正则表达式的工作。

你需要做这样的事情:

// 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...");
}
于 2011-10-15T21:18:02.393 回答
0

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

这样它应该可以工作:

if (strpos($entry, "http://") !== false || strpos($entry, "https://") !== false || strpos($entry, ".com") !== false)
于 2011-10-15T21:06:01.630 回答
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 。

于 2011-10-15T21:12:01.637 回答