文章正文匹配处理加A标签,redis缓存读取
- 共 3,290 次检阅

$content = '当顺利入职时,这只是线上企业培训机构第一步,试用期更重要,这个时候一定要谦虚谨慎。究其原因,是高级员工排他性强,愿意以资富文hr历荆门人才网取MBA其人力资源在职研究生航空招聘精华,欺人太甚。这个时候,我们一定要航空招聘牢记“谦虚谨慎”。勤奋、认真、认真地工作,多MBA读、多绩效考核学、多问,热情但不多言,尊重他人。与人好胜,做事粗心大意是禁忌。';
function sk_ilink($content, $blank = true, $num = 10)
{
    $connection=  mysqli_connect('127.0.0.1','root','123456','text');

    if(!$connection){
        exit('<h1>数据库连接失败</h1>');
    }
    $link = mysqli_query($connection,'select keyword,url from dr_1_ilink');

    //创建redis缓存
    $redis = new redis();
    $redis->connect('127.0.0.1', 6379);
    $keywords = $redis->get('keywords');

    //判断缓存是否存在
    if(empty($keywords)){
        $redis->setex('keywords','10000',json_encode($link));
        $keywords = $redis->get('keywords');
        $linksw = json_decode($keywords,true);
    }else{
        $links = json_decode($keywords,true);
    }

    //遍历从数据库拿出来的数组
    foreach ($link as $value){
        $links[] = $value;
    }

    //开始执行
    if (!$content) return '';
    if ($links) {
        $i = 0;
        foreach ($links as $k => $t) {
            // 总替换次数
            if ($i >= 4) {
                break;
            }
            if (strpos($content, $t['keyword']) !== false) {
                if (null && dr_now_url() == $t['url']) {
                    continue;
                }
                //同一个词替换次数
                $url = '<a href="' . $t['url'] . '" ' . (1 ? 'target="_blank"' : '') . '>' . $t['keyword'] . '</a>';
                $pattern  = '\'' . generate_preg('a',$t['keyword']) . '\'si';
                $content = @preg_replace(
                    $pattern,
                    $url,
                    $content,
                    1
                );
                ++$i;

            }
        }
    }
    return $content;
}

function generate_preg($tag_str, $name)
{
    $tag_array =  explode(',', $tag_str);
    $pattern_start = '(?!(' . generate_quote($tag_array, 'start') . '))(';
    $pattern_end = ')(?!(([^<>]*?)>)|' . generate_quote($tag_array, 'end') . ')';

    $pattern = $pattern_start . preg_quote($name) . $pattern_end;

    return $pattern;
}

function generate_quote($matches, $position)
{
    $tag_quote = [];
    foreach ($matches as $tag) {
        switch ($position) {
            case 'start':
                $tag_quote[] = "(<$tag.*?)";
                break;
            case 'end':
                $tag_quote[] = "([^>]*?</$tag>)";
                break;
            default:
                break;
        }
    }
    $tag_quote = implode('|', $tag_quote);
    return $tag_quote;
}

print_r(sk_ilink($content));

 

分享到:

这篇文章还没有评论

发表评论