请帮助我修复这个PHP while语句

请帮助我修复这个PHP while语句,php,debugging,while-loop,Php,Debugging,While Loop,下面的脚本应该在字符串中找到“最佳匹配”时结束,但即使我知道它最终被找到,脚本仍会继续运行。请帮我纠正我的错误 $end = "1"; while ($end != 2) { foreach($anchors as $a) { $i = $i + 1; $text = $a->nodeValue; $href = $a->getAttribute('href'); //if ($i<80) { //if (strpos($i

下面的脚本应该在字符串中找到“最佳匹配”时结束,但即使我知道它最终被找到,脚本仍会继续运行。请帮我纠正我的错误

$end = "1";
while ($end != 2) {
foreach($anchors as $a) { 
    $i = $i + 1;
    $text = $a->nodeValue;
    $href = $a->getAttribute('href');


        //if ($i<80) {
    //if (strpos($item, ".$array.") == false) {


    //}
      if (strpos($text, "best match") == true) {
$end = "2";
}
   if (strpos($text, "by owner") === false) {
       if (strpos($text, "map") === false) {
   if ($i > 17) {

     echo "<a href =' ".$href." '>".$text."</a><br/>";

}
   }

   }

    }
        //$str = file_get_contents($href);
//$result = (substr_count(strip_tags($str),"ipod"));
//echo ($result);



}
$end=“1”;
而($end!=2){
foreach($a){
$i=$i+1;
$text=$a->nodeValue;
$href=$a->getAttribute('href');
//如果有的话(17美元){
回声“
”; } } } } //$str=file\u get\u contents($href); //$result=(子项计数(带标签($str),“ipod”); //回声($结果); }
问题在于嵌套循环。当找到“最佳匹配”时,还需要结束foreach循环。尝试:

if (strpos($text, "best match") == true) {
    $end = 2; 
    break; # Terminate execution of foreach loop
}

在您的
strpos
中,您正在与true进行比较,这是错误的。
另外,在thasif语句中,您应该中断foreach和while循环

这是正确的代码:

<?php

while ($end != 2) {

  foreach($anchors as $a) {
    $text = $a->nodeValue;
    $href = $a->getAttribute('href');

    if (strpos($text, "best match") !== false) {
      $end = "2"; 
      break 2;
    }

    if (strpos($text, "by owner") === false) {
      if (strpos($text, "map") === false) {
        if ($i > 17) {
          echo "<a href =' ".$href." '>".$text."</a><br/>";
        }
      }
    }
  }
}

修复缩进,您就会看到问题。为什么
$end
是一个字符串,可以是
“1”
“2”
,并与整数进行比较?为什么不把它变成布尔值呢?为什么不直接使用
break 2
?如果
strpos
的结果是
0
,它将不会与
true
进行比较(无论如何,这是一个无意义的比较)。不,这不起作用):@scoota269。我认为应该是
break2
退出
foreach
while