RegEx表达式用于查找href链接并向其添加NoFollow

Rod*_*ney 3 regex

我正在尝试编写一个RegEx规则来查找我的网页上的所有href HTML链接,并向他们添加'rel ="nofollow"'.

但是,我有一个必须排除的URL列表(例如,任何(通配符)内部链接(例如pokerdiy.com) - 所以我的域名所在的任何内部链接都不包括在内.我想成为能够在排除列表中指定确切的URL - 例如 - http://www.example.com/link.aspx)

到目前为止,这是我的工作:

(] +)(HREF ="HTTP:?!//.*((pokerdiy))[^>] +>)

如果您需要更多背景/信息,可以在此处查看完整的主题和要求(跳过顶部以获取信息):http: //www.snapsis.com/Support/tabid/601/aff/9/aft/ 13117/AFV /主题/ afpgj/1/Default.aspx的#14737

par*_*ara 10

詹姆斯正则表达式的改进:

(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>
Run Code Online (Sandbox Code Playgroud)

此正则表达式将匹配字符串数组$ follow_list中的链接.字符串不需要前导'www'.:)优点是这个正则表达式将保留标记中的其他参数(如目标,样式,标题......).如果rel标记中已存在参数,则正则表达式将不匹配,因此您可以强制关注不在$ follow_list中的网址

替换为:

$1$2$3"$4 rel="nofollow">
Run Code Online (Sandbox Code Playgroud)

完整示例(PHP):

function dont_follow_links( $html ) {
 // follow these websites only!
 $follow_list = array(
  'google.com',
  'mypage.com',
  'otherpage.com',
 );
 return preg_replace(
  '%(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>%',
  '$1$2$3"$4 rel="nofollow">',
  $html);
}
Run Code Online (Sandbox Code Playgroud)

如果你想覆盖rel什么,我会使用一种preg_replace_callback方法,在回调中rel属性被单独替换:

$subject = preg_replace_callback('%(<a\s*[^>]*href="https?://(?:(?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"[^>]*)>%', function($m) {
    return preg_replace('%\srel\s*=\s*(["\'])(?:(?!\1).)*\1(\s|$)%', ' ', $m[1]).' rel="nofollow">';
}, $subject);
Run Code Online (Sandbox Code Playgroud)


Jam*_*bet 6

我开发了一个稍微强大的版本,可以检测锚标签中是否已经有"rel =",因此不会复制属性.

(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!blog.bandit.co.nz)[^"]+)"([^>]*)>
Run Code Online (Sandbox Code Playgroud)

火柴

<a href="http://google.com">Google</a>
<a title="Google" href="http://google.com">Google</a>
<a target="_blank" href="http://google.com">Google</a>
<a href="http://google.com" title="Google" target="_blank">Google</a>
Run Code Online (Sandbox Code Playgroud)

但不匹配

<a rel="nofollow" href="http://google.com">Google</a>
<a href="http://google.com" rel="nofollow">Google</a>
<a href="http://google.com" rel="nofollow" title="Google" target="_blank">Google</a>
<a href="http://google.com" title="Google" target="_blank" rel="nofollow">Google</a>
<a href="http://google.com" title="Google" rel="nofollow" target="_blank">Google</a>
<a target="_blank" href="http://blog.bandit.co.nz">Bandit</a>
Run Code Online (Sandbox Code Playgroud)

替换使用

$1$2$3"$4 rel="nofollow">
Run Code Online (Sandbox Code Playgroud)

希望这有助于某人!

詹姆士