如果使用PHP没有标题标记,则添加nofollow属性到链接


Add a nofollow attribute to link if no title tag present using PHP

我有一堆带有html的文本。基本上,我想做的是,对于在这篇文本中找到的所有链接,我只想在没有title属性的情况下,为找到的每个链接添加一个rel="noindex"。

例如,如果链接看起来像这样:

<a href="test.html">test</a>

我希望它看起来像:

<a rel="nofollow" href="test.html">test</a>

但如果链接看起来像这样:

<a title="test title" href="test.html">test</a>

我不想添加rel="nofollow"属性。我如何在php中做到这一点?

编辑:

很抱歉我没有提到这一点,但我正在使用PHP4。是的,我知道,但我被PHP4卡住了。

使用DOMDocument:非常简单

$dom = new DOMDocument;
$dom->loadHTML($yourHTML);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    if (!$link->hasAttribute('title')) {
        $link->setAttribute('rel', 'nofollow');
    }
}
$yourHTML = $dom->saveHTML();

这比使用regex要稳定可靠得多。

首先使用preg-match来获取是否添加了标题。

$str = '<a href="test.html">test</a>';
if(!preg_match('/title=/', $str))
{
    $str = str_replace('href=', 'rel="nofollow" href=', $str);
}