使用下面数组中的关键字列表:
$keywordlist = array(
'Apple iPhone' => 'http://www.example.com/apple/iphone/',
'Apple iPad' => 'http://www.example.com/apple/ipad',
'Samsung Galaxy Ace' => 'http://www.example.com/samsung/galaxy-ace',
'Samsung Galaxy Nexus' => 'http://www.example.com/samsung/galaxy-nexus',
'Samsung' => 'http://www.example.com/samsung/',
'Apple' => 'http://www.example.com/apple/'
);
我想将关键字替换为与其关联的URL。
我尝试过循环使用它们,并使用str_replace
和preg_replace
,但这将替换所有关键字中的制造商名称,因此所有关键字都将变成"三星"one_answers"苹果"的链接。我有点困惑于下一步该去哪里,有人有什么建议吗?
编辑:
我用下面的代码循环通过-
foreach($keywordlist as $name => $link){
$content = str_replace($name, '<a href="'.$link.'">'.$name.'</a>', $content);
}
解决方案:
我相信问题出在我替换的链接文本上。然后它又被其他关键词相似的短语取代了,我有下面的工作。
有人想到更好的方法吗?
$content = "<p>This Apple iPhone is from Apple</p>
<p>This Apple iPad is from Apple</p>
<p>This Samsung Galaxy Ace is from Samsung</p>
<p>This Samsung Galaxy Nexus is from Samsung</p>
<p>This is a Samsung</p>
<p>This is an Apple</p>";
$keywordlist = array(
'Apple iPhone' => '[1]',
'Apple iPad' => '[2]',
'Samsung Galaxy Ace' => '[3]',
'Samsung Galaxy Nexus' => '[4]',
'Samsung' => '[5]',
'Apple' => '[6]'
);
$content = str_replace(array_keys($keywordlist), array_values($keywordlist), $content);
$urllist = array(
'[1]' => '<a href="http://www.example.com/apple/iphone/">Apple iPhone</a>',
'[2]' => '<a href="http://www.example.com/apple/ipad">Apple iPad</a>',
'[3]' => '<a href="http://www.example.com/samsung/galaxy-ace">Samsung Galaxy Ace</a>',
'[4]' => '<a href="http://www.example.com/samsung/galaxy-nexus">Samsung Galaxy Nexus</a>',
'[5]' => '<a href="http://www.example.com/samsung/">Samsung</a>',
'[6]' => '<a href="http://www.example.com/apple/">Apple</a>'
);
$content = str_replace(array_keys($urllist), array_values($urllist), $content);
echo $content;
输出:
这款苹果iPhone来自苹果
这款苹果iPad来自苹果
这款三星Galaxy Ace来自三星
这款三星Galaxy Nexus来自三星
这是三星
这是一个苹果
str_replace()
应该足以满足您的尝试。
foreach($keywordlist as $key => $link) {
$content = str_replace($key, '<a href="$link">$key</a>', $content);
}
正如我所评论的,这将不会像预期的那样工作,因为键上重复重复的关键字。
你需要有一个固定的格式来表示一个键。我建议的是[Apple]
和[Apple iPad]
。当您实现类似的东西时,每个关键字都会不同,尽管它们内部包含相同的内部代码。
你更新后的关键词结构看起来像这样,在病房之后。
$keywordlist = array(
'[Apple iPhone]' => 'http://www.example.com/apple/iphone/',
'[Apple iPad]' => 'http://www.example.com/apple/ipad',
'[Samsung Galaxy Ace]' => 'http://www.example.com/samsung/galaxy-ace',
'[Samsung Galaxy Nexus]' => 'http://www.example.com/samsung/galaxy-nexus',
'[Samsung]' => 'http://www.example.com/samsung/',
'[Apple]' => 'http://www.example.com/apple/'
);
如果这样的话,选项是不可行的,因为这会显著增加开发内容的复杂性,因为需要用[]
包装每个关键字文本。
这对我来说有点没用,因为你有相同的键和值。也许我误解了你的意图。但你可以这样做:这使得密钥与值(url的)相同
$newkeywordlist = array_combine (array_values($keywordlist),array_values($keywordlist));
http://nl.php.net/manual/en/function.array-combine.php
http://nl.php.net/manual/en/function.array-values.php
您可以使用这个:
$s = "this is a test";
$arr = array(
"this" => "THIS",
"a" => "A"
);
echo str_replace(array_keys($arr), array_values($arr),$s);
输出:
THIS is A test