PHP 查找字符串并验证它

PHP finding string and validating it

我有一个数据库 table,其中事件由用户(第 "description" 列)描述并标记(第 "tag" 列)。 我想检查"description"中是否出现了某串字词,有些标签是无效的。

这是我目前所做的:

$sql = "SELECT * FROM events WHERE user='{$_SESSION['username']}'";
$qsql = mysql_query($sql) or die ("Error Query [".$sql."]");
while($result = mysql_fetch_array($qsql)){
   $description = mysql_real_escape_string(strtolower($result["description"]));
   $a = "string I want to find";
   $aa = strpos($description, $a);

     if (($aa !== false) AND $result["tag"]!=='1'){
     echo "The string you wrote doesn't allow the tag you used.";
     }
}

上面的代码有效。如您所见,如果给定的标记不是 1,则会回显一条错误消息。

但是,当我需要根据两个或更多标签验证字符串时遇到问题:

if (($aa !== false) AND ($result["tag"]!=='1' OR $result["tag"]!=='2')){
echo "The string you wrote doesn't allow the tag you used.";
}

即使给出标签 1 或标签 2,也会回显错误。 我不明白这有什么问题。

如果使用'OR',则表示"Show the error if its not 1 Or its not 2"。 如果 ['tag'] 是 '1',那么它就不是 '2',如果 ['tag'] 是 '2' 那么它就不是 '1',所以它永远为真。将其更改为 'AND' 将解决此问题。

您的代码应该是:

if (($aa !== false) AND $result["tag"]!=='1' AND $result["tag"]!=='2'){
  echo "The string you wrote doesn't allow the tag you used.";
}