如果域在阵列中,Php会将nofollow添加到链接中吗?

时间:2013-11-19 17:46:06

标签: php regex arrays preg-replace domparser

如何检查相同的字符串中是否存在数组中存储的域列表中的一个或多个链接到它们?

数组:

array  = ('example.com','domain.com','example.net')

和文字:

Lorem ipsum <a href="http://example.net">dolor sit amet</a>, consectetur adipiscing <a href="http://domain.com">elit</a>. 
Quisque quam urna, <a href="http://example.com/some-page/">hendrerit ut</a> vestibulum sit amet, elementum interdum dolor.

我想要做的是在链接中添加nofollow(如果它们存在于数组中)。

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

不要使用正则表达式解析HTML。请改用DOM解析器。

function getRootDomain($url) 
{
    // @ http://stackoverflow.com/a/19068356/1438393
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
}

// your domains array
$domains = array('example.com','domain.com','example.net');

$dom = new DOMDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 

// loop through all links
foreach ($dom->getElementsByTagName('a') as $link) {
    $href = $link->getAttribute('href');
    if (in_array(getRootDomain($href), $domains)) {
        $link->setAttribute('rel', 'nofollow');
    }
}

echo $dom->saveHTML();

Demo!

答案 1 :(得分:0)

我对此有间接的解决方案。 使用jquery和一个外部php文件。

<script type="text/javascript">
var link=$("a").attr("href");
$.ajax({
                type:"POST",
                //data:"",
                url:"http://www.yourdomain.com/yourfile.php?link"+link,
                success: function(data){ 
                //get the response from the php file and add the nofollow tag if the response says so.

                }, //end of success
                error: function(){
                    //code if error
                    }// end of error
            });
</script>

你的php文件将是:

<?php
$links_array = array('example.com','domain.com','example.net');
$link=$_GET['link'];
if (in_array($link, $links_array)) {
return true; //or something you can use
} else {
return false; //or something you can use
}
}
?>

将毫无问题地处理它。