繁体   English   中英

匹配单词(正则表达式)并根据存储在数组中的值创建内部链接

[英]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." ";
    }
}

但是我被正则表达式卡住了(我认为这是正确的方法)。

$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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM