今天我使用PHP DOMDocument类来查找源代码中的所有链接。 $ links数组包含来自网站的所有链接。函数'for'使用循环迭代查找给定$ domain。
<div class="wrapper" ng-click="$event.stopPropagation()" style="width: 100%; height: 300px; background:grey;">
<div class="btn-group" uib-dropdown>
<button id="split-button" type="button" class="btn btn-danger">Action</button>
<button type="button" class="btn btn-danger" uib-dropdown-toggle>
<span class="caret"></span>
<span class="sr-only">Split button!</span>
</button>
<ul class="dropdown-menu" uib-dropdown-menu role="menu" aria-labelledby="split-button">
<li role="menuitem"><a href="#">Action</a></li>
<li role="menuitem"><a href="#">Another action</a></li>
<li role="menuitem"><a href="#">Something else here</a></li>
<li class="divider"></li>
<li role="menuitem"><a href="#">Separated link</a></li>
</ul>
</div>
示例:
搜索域名:http://example.com 搜索网址:http://www.iana.org
结果:
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("@$domain@i", $links[$i]['href']);
if($find_href)
{
if($links[$i]['href'] != "")
{
echo $links[$i]['anchor'];
echo 'Link found';'
}
else
{
echo 'Link not found';
}
搜索域名:http://example.com 搜索链接:http://google.com
结果:
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
如果在$ links数组中找不到$ domain,如何打印一次“链接未找到”?
答案 0 :(得分:0)
每次for循环使用变量'$ i'执行+ 1。创建一个变量'$ total'并计算'$ links',然后在for循环中执行:
<!-- above the for loop -->
$total = count($links);
<!-- in the for loop -->
if ($i == $total) {
echo 'Link not found';
}
答案 1 :(得分: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("@$domain@i", $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("@$domain@i", $link['href']);
if($find_href) {
if($link['href'] != '') {
echo $link['anchor'] . "\nLink found";
$found = true;
}
}
}
if (!$found) {
echo 'Link not found';
}