我正在为我们的网站编写一个基本的邮件列表系统。 “subscribe.php”页面对参数使用$_GET
方法。我将电子邮件地址添加到文本文件 (maillist.txt) 中。
在添加地址之前,我检查它是否还不在文件中。
问题:比较两个相同的字符串返回 false..
我尝试过的:
- 我确定 maillist.txt 是 UTF-8 格式
- 我尝试在 UTF-8 中设置 header
- 我试过使用 strcmp()
- 我尝试用 utf8_encode 转换两个字符串
这是“subscribe.php”代码:(我删除了所有正则表达式和 isset 检查)
<?php
// UTF-8 ----> things I've added, trying to solve the problem
header('Content-Type: text/html; charset=utf-8');
ini_set('default_charset', 'utf-8');
ini_set("auto_detect_line_endings", true);
$email = strip_tags($_GET['email']); // For safety
$maillist = fopen('maillist.txt', 'r+');
// Check if email is already in the database
$insert = true;
while ($line = fgets($maillist)) {
$line = rtrim($line, "\r\n");
if (utf8_encode($line) == utf8_encode($email)) { // $line == $email returns false
echo $line . "=" . $email . "<br/>";
$insert = false;
break;
} else echo $line . "!=" . $email . "<br/>";
}
if ($insert) {
fputs($maillist, $email . "\n");
echo 'Success';
} else echo "Fail";
fclose($maillist);
?>
最佳答案
在这里黑暗中拍摄...
首先,将您的值存储为变量并重复使用这些值,您打印的内容可能与您正在比较的内容不同。
修剪这些变量以确保前后没有任何无关的空格。
while ($line = fgets($maillist)) { $line = rtrim($line, "\r\n"); //the two variables you want to compare $lineValue = trim(utf8_encode($line)); $email = trim(utf8_encode($email)); //compare them them out if ($lineValue == $email) { echo $lineValue . "==" . $email . "<br/>"; //compare the trimmed variables $insert = false; break; } else { echo $lineValue . "!=" . $email . "<br/>"; } }
这甚至可能不是你的问题,但如果你用眼睛看到相同的字符串,这是一个很好的起点..
关于php - 字符串比较返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18263732/