问题描述
我有一个像这样的数组:
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)
SEO进行自动关键字链接是否安全?
and is it safe for SEO to make this automated keyword linking?
有什么想法吗?
推荐答案
$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 = '/\b(' . preg_quote(implode('|', $keywords), '/') . ')\b/i';
preg_replace_callback($regex, $linker, $string);
使用正则表达式的优势在于我们可以利用 \ b
修饰符来确保捕获诸如(php)
, PHP之类的情况.
或 phpp
并正确处理它们.
Advantage of using regular expressions is that we can leverage the \b
modifier to ensure we catch cases such as (php)
, PHP.
, or phpp
and deal with them properly.
这篇关于扫描字符串并用链接替换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!