使用数组替换确切的单词

时间:2013-06-20 13:06:26

标签: php

我有一系列值和链接,需要只用链接替换内容中的确切值一次。 对于这个preg_replace可以帮助:

Array ( 
[0] => Array ( [keyword] => this week [links] => http://google.com ) 
[1] => Array ( [keyword] =>this [links] => http://yahoo.com ) 
[2] => Array ( [keyword] => week [links]=> http://this-week.com ) ) 
) 

案文是:

$content = "**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.";

我尝试使用字符串替换 - 因为数组可以用于字符串替换,但随后会替换所有出现的字符串。 我尝试使用带位置的substr_replace,但它不能像我想的那样工作。

$pos = strpos($content,$keyword);
if($pos !== false){
    substr_replace($content,$link,$pos,strlen($keyword));
}

和preg_replace,带有循环数组:

preg_replace('/'.$keyword.'/i', $link, ($content),1);

它有点工作,它只替换带链接的关键字一次,但如果关键字是复合(本周),则替换为 this ,这是错误的......

非常感谢你的帮助......谢谢。

更新

$ link是问题 - 如果没有'http://'工作正常... 现在这是有问题的,如何摆脱它...

3 个答案:

答案 0 :(得分:1)

我编写了替换所有值的代码示例。我不知道你想要替换的文本到底是什么,所以我放了示例文本

 $content = "**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.**This week** I'd like to go to the seaside, but the weather is not good enough. Next **week** will be better. **This** is a kind of great news.";
 $replacement = array('[linkthiswWeek]', '[links_this]','[links_Week]');
 $patterns = array('/This week/', '/This/', '/week/');
 echo preg_replace($patterns, $replacement, $content);

<强>输出:

**[linkthiswWeek]** I'd like to go to the seaside, but the weather is not good enough. Next **[links_Week]** will be better. **[links_this]** is a kind of great news.**[linkthiswWeek]** I'd like to go to the seaside, but the weather is not good enough. Next **[links_Week]** will be better. **[links_this]** is a kind of great news.**[linkthiswWeek]** I'd like to go to the seaside, but the weather is not good enough. Next **[links_Week]** will be better. **[links_this]** is a kind of great news.

您可以通过修改$replacement数组

来满足您的需求

答案 1 :(得分:1)

罗伯特的答案有效,但取代了每次出现,这不是必需的。在preg替换的末尾添加“,1”仅替换每次出现的次数。

e.g。 echo preg_replace($ patterns,$ replacement,$ content,1);

答案 2 :(得分:1)

如果您使用某种“ID”代替链接,在preg_replace中使用它,如果这样做,您可以调用str_replace并用真实链接替换ID吗?

$content = preg_replace('/'.$keyword.'/i', $IDS, ($content),1);
$content = str_replace($IDS, $link, $content);