Blorner

Wednesday, November 17, 2010

Retrieve links and sort them by follow or nofollow

This PHP example is used to retrieve all links from a file content or a url content, then sort by the follow links or nofollow links and show them:

<?php
$file = "http://example.com";

$content = file_get_contents($file);
$links = array("follow"=>array(),"nofollow"=>array());

preg_match_all("/(<a.*>)(.*)(<\/a>)/ismU",$content,$matches,PREG_SET_ORDER);

if(empty($matches)){
echo("There is no link in the file ".$file.".");
}else{
foreach($matches as $match){
preg_match("/href\s*=\s*[\'|\"]\s*([^\"|\']*)\s*[\'|\"]/i",$match[1],$href);

if(preg_match("/rel\s*=\s*[\'|\"]\s*nofollow\s*[\'|\"]/i",$match[1])){
$links["nofollow"][] = $href[1];
}else{
$links["follow"][] = $href[1];
}
}

$output = "<h1>Nofollow links</h1>";

if(empty($links["nofollow"])){
$output .= "There is no nofollow link.";
}else{
$output .= "<ol type='1'>";

foreach($links["nofollow"] as $link){
$output .= "<li>".$link."</li>";
}

$output .= "</ol>";
}

$output .= "<h1>Follow links</h1>";

if(empty($links["follow"])){
$output .= "There is no follow link.";
}else{
$output .= "<ol type='1'>";

foreach($links["follow"] as $link){
$output .= "<li>".$link."</li>";
}

$output .= "</ol>";
}

echo($output);
}
?>

No comments:

Post a Comment

Art Works Expo