PHP在内容文本中查找标签,并换成<a> tags and set limit the number of links

时间:2019-02-13 11:16:00

标签: php

Im finding keywords "denounce,and,demoralized" in a string, and wrapping it in "html a" tags to change it to link with following function...

 function link2tags($text, $tags){
        $tags = preg_replace('/\s+/', ' ', trim($tags));
        $words = explode(',', $tags);

        $linked = array();
        foreach ( $words as $word ){
            $linked[] = '<a href="'.$word.'">'.$word.'</a>';
        }

        return str_replace($words, $linked, $text);
    }

echo link2tags('we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment', 'denounce,and,demoralized');

The output of the above function is as follows...

Output:

we <a href="denounce">denounce</a> with righteous indignation <a href="and">and</a> dislike men who are so beguiled <a href="and">and</a> <a href="demoralized">demoralized</a> by the charms of pleasure of the moment

Here, the word "and" is linked 2 times I want to limit the number of links to a word Repeat words are only linked once

2 个答案:

答案 0 :(得分:0)

您可以在此处检查现有单词,如下所示:

if(!in_array($word,$alreadyusedword)) {
      $linked[] = '<a href="'.$word.'">'.$word.'</a>';
      $alreadyusedword[] = $word;
}

答案 1 :(得分:0)

您只需要首先出现单词,然后替换它们即可。检查以下代码:

   function link2tags($text, $tags){
        $tags = preg_replace('/\s+/', ' ', trim($tags));
        $words = explode(',', $tags);

        $linked = array();
        $existingLinks = array();
        foreach ( $words as $word ){
            if (!in_array($word, $existingLinks)) {
                $existingLinks[] = $word;
                $linked[] = '<a href="'.$word.'">'.$word.'</a>';                
            }
        }

        foreach ($existingLinks as $key => $value) {
            $text = preg_replace("/".$value."/", $linked[$key], $text, 1);
        }
        return $text;
    }

希望它对您有帮助。