Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

php - scan a string and replace tags with links

I have an array like this:

$keywords = array( 'php', 'html', 'css' );

I have a db query to return a paragraph, which contains the keywords previously mentioned in the array.

I have a link template like this:

$linktpl = '<a href="%s" title="%s">%s</a>';

I want a simple function to scan that paragraph and on the fly, whenever it finds a keyword it converts it to a link using the link template above.

And if possible I want it to take into account singular and plural (like framework and frameworks)

and is it safe for SEO to make this automated keyword linking?

Any Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$string = 'this is the php test subject.';

// associate keywords with their urls
$urls = array(
'php' => 'http://www.php.net',
// and etc...
);

// this callback will take the matches from preg and generate the
// html link making use of the $urls dictionary
$linker = function($matches) use($urls) {
    $urlKey = strtolower($matches[1]);
    return sprintf(
      '<a href="%s" title="%s">%s</a>',
      $urls[$urlKey], $matches[1], $matches[1]
    );
};

// do the magic
$regex = '/(' . preg_quote(implode('|', $keywords), '/') . ')/i';
preg_replace_callback($regex, $linker, $string);

Advantage of using regular expressions is that we can leverage the modifier to ensure we catch cases such as (php), PHP., or phpp and deal with them properly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...