php - 扫描字符串并用链接替换标签

标签 php arrays str-replace

我有一个这样的数组:

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

我有一个数据库查询返回一个段落,其中包含数组中前面提到的关键字。

我有一个这样的链接模板:

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

我想要一个简单的函数来快速扫描该段落,每当它找到关键字时,它就会使用上面的链接模板将其转换为链接。

如果可能的话,我希望它考虑单数和复数(比如 framework 和 frameworks)

SEO 进行自动关键字链接是否安全?

有什么想法吗?

最佳答案

$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 并妥善处理它们。

关于php - 扫描字符串并用链接替换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5889873/

相关文章:

php - 注销后浏览器后退按钮

php - Str_replace 用于多个项目

python - 使用 Cython 包装 C++ 模板以接受任何 numpy 数组

javascript - 如何在 JavaScript 公式中用字符串替换整数

php 字符串仅在 html 标签内替换,即字符串的 <here>

php - 如何将 Doctrine 注入(inject) Symfony2 服务

php - 如何从多个表中获取数据并在laravel中使用 '->with()'发送到html

javascript - 无法超出 SetInterval 返回值

javascript "header"文件存储一些数据

python - numpy数组:快速填充和提取数据