用户输入的字符串,当包含某些特殊字符时,与数据库字符串不匹配,尽管它们看起来是等效的字符串


User inputted string, when containing certain special characters, does not match database string though they appear to be equivalent strings

我搜索了类似的问题,发现了这个但这对我的处境没有帮助。在我的网站上,用户输入一个答案。该字符串通过ajax调用发送到php文件。字符串可以包含也可以不包含特殊字符,所以我使用

encodeURIComponent()

在字符串被发送到PHP文件之前。

在php文件中将用户输入的字符串与代表"正确答案"的字符串进行比较,如果处理后发现字符串是等效字符串,则用户输入的答案为"正确"。直到今天,我还没有遇到任何弦的问题。直到今天,包含字母、特殊字符(括号、负号、加号)和数字的字符串在php中使用以下处理都可以正常工作:

<?php include 'connect.php';
$UserInput = trim($_GET['userinput']);
$QID = mysqli_real_escape_string($cxn, $_GET['qid']);
$sqlIQ = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT answer FROM IndexQuestions WHERE sampqid = $QID"));

$StrReplaceArray = array("<i>", "</i>", "</sup>", " ");
$CorrectAnswer1 = str_replace($StrReplaceArray, "", $sqlIQ['answer']);
$CorrectAnswer2 = str_replace("<sup>", "^", $CorrectAnswer1);
$UserAnswer1 = str_replace(" ", "", $UserInput);
$UserAnswer2 = str_replace("+-", "-", $UserAnswer1);
if (strcasecmp($UserAnswer2, $CorrectAnswer2) == 0) {
    $CorrectOrNot = 'Correct';
} else {
    $CorrectOrNot = 'Incorrect';
}

但是,最新的字符串不能工作。用户输入的字符串为-2±√3,作为 -2 &plusmn; &radic;3 (带或不带空格)发送到php文件。保存在另一个表中的"正确答案"是 -2 &plusmn; &radic;3 。我重复了以下内容:

echo $UserAnswer2 . " " . $CorrectAnswer2; //after str_replace processing shown above

和每个变量的HTML输出在我看来是相同的。我还尝试了以下比较目的(而不是strcasecmp):

if ($UserAnswer2 == htmlentities($CorrectAnswer2)) { //etc.

,但还是一样的。

当我检查一个单独的表(存储用户的答案)时,答案以我想要的方式存储:

$unixtime = time();
$AnswerID = substr(md5(rand(0, 1000000)), 0, 10).$unixtime;
$sqlIQStats = mysqli_query($cxn, "INSERT INTO IQStats (answer_id, useranswer) VALUES ('$AnswerID', '".htmlentities($UserAnswer2)."')");

,在数据库中显示为 -2 &plusmn; &radic;3

网站使用的html字符集是charset=utf-8

$UserInput和$UserAnswer2都给出字符串(8)"-2±√3"而$CorrectAnswer2给出字符串(18)"2±√3"

有没有人有任何想法,为什么字符串,字符串处理和比较后,在php文件中,被发现是不相等的字符串?

OK…通过将$UserInput更改为:

解决了这个问题
$UserInput = htmlentities(trim($_GET['userinput']));