使用正则表达式如何使一些URL变为no-follow?

5

好的,我已经制作了这个函数,可以将大多数URL(如pies.com或www.cakes.com)转换为实际的链接标签。

function render_hyperlinks($str){       
    $regex = '/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org(\.uk)?|tv|biz|me)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/ie';    
    $str = preg_replace($regex,"'<a href=\"http://www.'.'$3'.'\" target=\"_blank\">'.strtolower('$3').'</a>'", $str);
    return $str;    
}

我希望更新这个功能,将no-follow标签添加到指向我的竞争对手的链接中,
所以我会选择某些关键词(竞争对手名称)来进行nofollow。例如,如果我的网站是关于烘焙的,我可能想要:
no-follow any sites with the phrases 'bakingbrothers', 'mrkipling', 'lyonscakes'

能否将if(contains x){ add y}实现到我的正则表达式中?

这就是所谓的“回溯”吗?

1个回答

2
也许 preg_replace_callback 是你要寻找的内容:
function link($matches)
{
    $str_return = '<a href="http://www.'.$matches[3].'" target="_blank"';
    if(in_array($matches[3], $no_follow_array))
    {
        $str_return .= ' no-follow';
    }
    $str_return .='>'.strtolower($matches[3]).'</a>';
}

$regex = '/(http:\/\/)?(www\.)?([a-zA-Z0-9\-_\.]+\.(com|co\.uk|org(\.uk)?|tv|biz|me)(\/[a-zA-Z0-9\-\._\?&=#\+;]+)*)/ie';    
$str = preg_replace_callback($regex,'link', $str);

这看起来很不错,但我遇到了字符问题。似乎 preg_replace_callback 不接受 'e' 修饰符,因此现在它正在捕获 '\n' 换行符的形式? - Haroldo
你能提供一个输入字符串的例子吗?盲目构建正则表达式很困难 :) - Narcis Radu
啊,那是我的错误,我将换行符双重转义了,你的解决方案非常好,同时也感谢 Marty 的帮助。 - Haroldo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接