Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果使用PHP不存在标题标记,则向链接添加nofollow属性_Php_Regex_Dom - Fatal编程技术网

如果使用PHP不存在标题标记,则向链接添加nofollow属性

如果使用PHP不存在标题标记,则向链接添加nofollow属性,php,regex,dom,Php,Regex,Dom,我有一堆包含html的文本。基本上,我想做的是,对于本文中找到的所有链接,我只想在title属性不存在的情况下,为找到的每个链接添加一个rel=“noindex” 例如,如果链接如下所示: <a href="test.html">test</a> <a title="test title" href="test.html">test</a> 我希望它看起来像: <a rel="nofollow" href="test.html">

我有一堆包含html的文本。基本上,我想做的是,对于本文中找到的所有链接,我只想在title属性不存在的情况下,为找到的每个链接添加一个rel=“noindex”

例如,如果链接如下所示:

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

我希望它看起来像:

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

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

<a 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();

这比使用正则表达式要稳定可靠得多。

如果添加了标题,首先使用preg-match

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

用于that@Ibu与使用本机函数执行此操作的难度相比,该库的开销是巨大的。