将PHP变量与文本文件中的值进行比较
我试图验证文本文件中是否存在php变量值,然后回显该值。使用下面的代码,只有当变量中的值等于文本文件中的最后一个值时,我的if语句才为true。如果变量中的值等于第一个、第二个、第三个等值,则If语句为false 这是我的密码:将PHP变量与文本文件中的值进行比较,php,arrays,foreach,text-files,strpos,Php,Arrays,Foreach,Text Files,Strpos,我试图验证文本文件中是否存在php变量值,然后回显该值。使用下面的代码,只有当变量中的值等于文本文件中的最后一个值时,我的if语句才为true。如果变量中的值等于第一个、第二个、第三个等值,则If语句为false 这是我的密码: $lines = file("file.txt"); $value = $_GET['value']; foreach ($lines as $line) { if (strpos($line, $value) !== false) {
$lines = file("file.txt");
$value = $_GET['value'];
foreach ($lines as $line) {
if (strpos($line, $value) !== false) {
$output = $line;
} else {
$output = "Sorry, we don't recognize the value that you entered";
}
}
如注释中所述,使用行数据或错误消息覆盖每个循环中的变量
foreach ($lines as $line) {
if (strpos($line, $value) !== false) {
$output[] = $line;
}
}
if(empty($output)){
echo "Sorry, we don't recognize the value that you entered";
} else {
print_r($output);
}
另一个答案会更正您的代码,但会将1个或多个代码与更少的代码匹配:
$output = preg_grep('/'.preg_quote($value, '/').'/', $lines);
要仅对1个匹配使用现有方法,然后将从循环中断开和/或在之前定义“对不起…”输出:
$output = "Sorry, we don't recognize the value that you entered";
foreach ($lines as $line) {
if (strpos($line, $value) !== false) {
$output = $line;
break;
}
}
每次都覆盖$output
变量。您希望得到什么?仅针对1个匹配:$output=$line;中断代码>谢谢AbraCadaver-这对我来说真的很有效。我也可以在_阵列中使用吗?if(在_数组中($value,$lines))仅当行和值相同时。意思是测试
将与测试行
等不匹配。。。