我想要实现的目标如下: 当我创建新闻项目时,我希望php检查这些项目的关键字。这些关键字存储在mysql表中(2个字段:search = varchar(255),link = varchar(255))。 我使用查询来获取结果并将它们存储在数组中。
我想在字符串中找到单词并在单词中添加锚点。重要的一点是(我遇到困难)是搜索必须不区分大小写。
例如:
$searchFor = array("sun","sunny","wind","crap");
$linkArray = array("/solar","/solar","/wind-energy","/toilet");
字符串:
你对太阳有什么了解?太阳,那是什么样的词?是吗 像风一样的东西?风,另一个奇怪的词。这个文本是 顺便提一下。
我想要的结果是:
您对sun了解多少? Sun那是什么意思?它是否像wind那样? Wind另一个奇怪的词。顺便说一句,此文字已完整crap。
我的代码是:
$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>';
这可能吗?
谢谢。
答案 0 :(得分:1)
<强> Testet!强>
<?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);