Php 如果匹配不是';在while循环中找不到,显示错误消息
如果在while循环中找不到匹配项,我试图显示一条错误消息“Match not found”。现在,我知道如果我在里面放一个“else”语句,它只会为每一行显示“matchnotfound”,直到它到达循环的末尾 以下是我目前掌握的情况:Php 如果匹配不是';在while循环中找不到,显示错误消息,php,if-statement,while-loop,preg-match,fopen,Php,If Statement,While Loop,Preg Match,Fopen,如果在while循环中找不到匹配项,我试图显示一条错误消息“Match not found”。现在,我知道如果我在里面放一个“else”语句,它只会为每一行显示“matchnotfound”,直到它到达循环的末尾 以下是我目前掌握的情况: <?php $filename = "roster.txt"; $fp = fopen($filename, "r") or die("Couldn't open $filename"); whi
<?php
$filename = "roster.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp))
{ $line = fgets($fp);
if (preg_match('/Navi/',$line)) {
print "$line<br>";
}
}
fclose($fp)
?>
我累了。。。这可能不是最优雅的方式,但它应该会起作用
$x=0;
while(!feof($fp))
{ $line = fgets($fp);
$answer = str_replace(":"," ",$line);
if ((preg_match("/$lastname/",$line)) && (preg_match("/$id/",$line))) {
print "$answer<br>";
$x = $x+1;
}
}
if($x==0) {
echo 'No match found';
}
$x=0;
而(!feof($fp))
{$line=fgets($fp);
$answer=str_replace(“:”,“”,$line);
if((preg_匹配(“/$lastname/”,$line))&&(preg_匹配(“/$id/”,$line))){
打印“$answer
”;
$x=$x+1;
}
}
如果($x==0){
回显“未找到匹配项”;
}
我会使用一个布尔值来跟踪是否找到该值,然后使用该值来选择性地显示未找到的消息:
生成一个局部变量以跟踪是否找到匹配项。例如,在psuedocode中:
int match_is_found = 0
loop :
// do stuff
if match was found:
match_is_found = 1
end loop
if match_is_found is 0:
display error message
(如果这对PHP没有帮助,很抱歉-从未使用过它)。在while循环之前将匹配设置为false
,在找到匹配时将其设置为true
。
while循环检查后匹配变量
$match = false;
while(!feof($fp))
{ $line = fgets($fp);
$answer = str_replace(":"," ",$line);
if ((preg_match("/$lastname/",$line)) && (preg_match("/$id/",$line))) {
$match = true;
print "$answer<br>";
}
}
if ($match === false) {
echo 'Match not found';
}
$match=false;
而(!feof($fp))
{$line=fgets($fp);
$answer=str_replace(“:”,“”,$line);
if((preg_匹配(“/$lastname/”,$line))&&(preg_匹配(“/$id/”,$line))){
$match=true;
打印“$answer
”;
}
}
如果($match==false){
回显“未找到匹配项”;
}
从概念上讲,这是可行的,但是您有一些语法错误-x
应该是$x
,因为它不是一个常量,您需要测试$x==0
,因为单个=
将赋值为0
。我倾向于使用布尔值,除非你关心有多少匹配没有找到。啊,初学者的错误。谢谢,编辑。这就是我想这样做的原因之一,它会为找到的数字返回一个值。不知道这是否必要,但无论哪种方式都不会影响性能。谢谢!这个很好,很简单!谢谢大家的帮助!
$match = false;
while(!feof($fp))
{ $line = fgets($fp);
$answer = str_replace(":"," ",$line);
if ((preg_match("/$lastname/",$line)) && (preg_match("/$id/",$line))) {
$match = true;
print "$answer<br>";
}
}
if ($match === false) {
echo 'Match not found';
}