匹配单词(regex)并根据存储在Array中的值创建内部链接


Match words (regex) and create internal links from values stored in Array

我正在努力实现以下目标:当我创建新闻项目时,我希望php检查这些项目的关键字。这些关键字存储在一个mysql表中(2个字段:search=varchar(255),link=varchar(255))。我使用查询来获取结果并将它们存储在数组中。

我想在字符串中查找单词,并为单词添加一个锚。重要的是(我有困难的地方)搜索必须不区分大小写。

例如:

$searchFor = array("sun","sunny","wind","crap");
$linkArray = array("/solar","/solar","/wind-energy","/toilet");

字符串:

你对太阳了解多少?孙,这是什么字?是吗像风一样的东西?风,另一个奇怪的词。此文本是顺便说一句,完全是垃圾。

因此,我想要的是:

你对太阳了解多少?孙,那是什么字?是不是有点像风?风又是一个奇怪的词。顺便说一句,这篇文章完全是垃圾。

我的代码是:

$string = 'What do you know about the sun? Sun, what kind of word is that? Is it something just like wind? Wind, another weird word. This text is complete crap by the way.';
$pattern = "/('w+)/i";
preg_match_all($pattern, $string, $matches);
foreach($matches[0] as $i => $word)
{
    $search = strtolower($word);
    if(in_array($search,$searchFor))
    {
        $pos = array_search($search,$searchFor);
        $link = $linkArray[$pos];
        echo "<a href='"{$link}'">{$word}</a> ";
    }
    else
    {
        echo $word." ";
    }
}

但是我一直在使用regex(我认为这是正确的方法)。

$replacement = '<a href="{$link}">${1}</a>';

这可能吗??

谢谢。

测试集

<?php
$searchFor = array("sun","sunny","wind","crap");
foreach($searchFor as $iKey => $sVal) {
    $searchFor[$iKey] = "/(" . $sVal . ")/i";
}
$linkArray = array("/solar","/solar","/wind-energy","/toilet");
foreach($linkArray as $iKey => $sVal) {
    $linkArray[$iKey] = '<a href="' . $sVal . '">$1</a>';
}
$string = 'What do you know about the sun? Sun, what kind of word is that? Is it something just like wind? Wind, another weird word. This text is complete crap by the way.';
echo preg_replace($searchFor, $linkArray, $string);