lukaswhite/auto-no-follow

使用PHP自动给HTML中的链接添加rel=nofollow属性

1.0.0 2019-01-14 09:19 UTC

This package is auto-updated.

Last update: 2024-09-14 21:21:05 UTC


README

这个简单的PHP包只有一个简单的目的;接收一些HTML(作为字符串),遍历它并将所有链接添加rel="nofollow"属性,但某些异常除外。

所以给它这个

<p>Check out our <a href="http://example.com">affordable web design services</a>!</p>

...你将得到这个

<p>Check out our <a href="http://example.com" rel="nofollow">affordable web design services</a>!</p>

默认情况下,它将忽略相对链接,因此这个将保持不变

<p>Check out the <a href="/about">about</a> page</p>

它还会忽略指向当前域的绝对链接。

您还可以提供一个域名白名单,并且它将跳过这些域名。

安装

composer require lukaswhite/auto-no-follow

使用方法

创建一个实例

$processor = new \Lukaswhite\AutoNoFollow\Processor();

可选地指定当前主机

$processor->setCurrentHost('example.com');    

如果您不设置,它将从$_SERVER['HTTP_HOST']中获取

然后运行

$html = $processor->addLinks('<p>Check out our <a href="http://example.com">affordable web design services</a>!</p>');

方法的签名是

public function addLinks($html, $whitelist = array(), $ignoreRelative = true)

所以,要为某些主机添加白名单

$html = $processor->addLinks(
  '<p>Check out our <a href="http://example.com">affordable web design services</a>!</p>'
  [
  	'example.com'
  ]
);

如果要无论如何添加相对链接的nofollow,请将第三个参数设置为true,例如

$html = $processor->addLinks(
  '<p>Check out the <a href="/about">about</a> page</p>'
  [],
  TRUE
);

这将输出以下内容

<p>Check out the <a href="/about" rel="nofollow">about</a> page</p>

测试

该包包含测试,要运行它们

./vendor/bin/phpunit