我尝试使用在此线程上找到的代码 Add rel="nofollow" and target="_blank" for external links permanently 问题在于它也在内部链接中添加了nofollow,noopener和_blank标签。仅应将其添加到外部链接。怎么了?谢谢
function add_nofollow_content($content) {
$content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i', function($m) {
if (strpos($m[1], "https://example.com/") === false)
return '<a href="'.$m[1].'" rel="nofollow noopener" target="_blank">'.$m[2].'</a>';
else
return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
}, $content);
return $content;
}
add_filter('the_content', 'add_nofollow_content');
答案 0 :(得分:0)
<?php
function replaceAnchorsWithText($data) {
$regex = '/<a .* href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i';//regex
if (is_array($data)) {
if (strpos($data[1], "https://example.com/") === false)
$data= '<a href="'.$data[1].'" rel="nofollow noopener" target="_blank">'.$data[2].'</a>';
else
$data='<a href="'.$data[1].'" target="_blank">'.$data[2].'</a>';
}
return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}
$output = replaceAnchorsWithText('<a href="https://example.co">A</a>
Link Must Be In New line<a href="https://example.com/">B</a>');
echo $output;