2016-11-24 43 views
2

今天我使用PHP DOMDocument类来查找源代码中的所有链接。 $ links数组包含来自网站的所有链接。函数'for'使用循环迭代来查找给定的$域。PHP - 在循环中显示'echo'一次

echo 'Find link: ' . $domain . ''; 
echo "<b>Status: "; 

//$links is array with all links 
//$domain is domain for example : http://example.com 

for($i = 0;$i<count($links);$i++) 
     { 
      $find_href = preg_match("@[email protected]", $links[$i]['href']); 

      if($find_href) 
      { 

        if($links[$i]['href'] != "") 
        { 
         echo $links[$i]['anchor']; 
         echo 'Link found';' 
        } 
        else 
        { 
         echo 'Link not found'; 
        } 

实施例:

搜索域:HTTP://示例.com 找遍的URL:http://www.iana.org

结果:

Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
http://www.iana.org/domains/example 
Link found // find bacouse link is in source code of http://example.com 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 

搜索域:http://example.com 已检索的链接:http://google.com

结果:

Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 
Link not found 

如果没有在发现$域$链接阵列,如何打印一次“链接没有发现”?

+0

你想,如果没有找到阻止你循环?或者只打印一次X消息的消息? –

+0

print_r($ links)的输出是什么,只需要一个输出示例 – Elby

+0

@RiggsFolly感谢您的关注 – limakg

回答

0

只需在一个变量登记到的情况,然后输出没有找到的消息后,环路根据你是否找到某种东西来完成。

echo 'Find link: ' . $domain . ''; 
echo "<b>Status: "; 

//$links is array with all links 
//$domain is domain for example : http://example.com 

$found = false; 

for($i = 0;$i<count($links);$i++) { 
    $find_href = preg_match("@[email protected]", $links[$i]['href']); 

    if($find_href) { 

     if($links[$i]['href'] != "") { 
      echo $links[$i]['anchor']; 
      echo 'Link found'; 
      $found = true; 
     } 
    } 
} 
if (!$found) { 
    echo 'Link not found'; 
} 

拿起收到的意见,这将是更好的代码

echo 'Find link: ' . $domain . ''; 
echo "<b>Status: "; 

//$links is array with all links 
//$domain is domain for example : http://example.com 

$found = false; 

foreach ($links as $link) { 
    $find_href = preg_match("@[email protected]", $link['href']); 

    if($find_href) { 
     if($link['href'] != '') { 
      echo $link['anchor'] . "\nLink found"; 
      $found = true; 
     } 
    } 
} 
if (!$found) { 
    echo 'Link not found'; 
} 
+0

只是一个小提示:在for循环前更好'count($ links)',而不是在里面。这样它会数数次,而不是只有一次。只是一个小的表演事物 – DasSaffe

+0

@DasSaffe是真的。不想改变太多原始代码并混淆OP – RiggsFolly

+0

更好的办法是使用'foreach()'而不是'for'。 – Barmar

0

每次for循环都会对变量'$ i'执行+1操作。做一个变量“$总”和计数“$链接”,然后在for循环,你只是做:

<!-- above the for loop --> 
$total = count($links); 

<!-- in the for loop --> 
if ($i == $total) { 
    echo 'Link not found'; 
}