0

我有一组值和链接,并且只需要用链接替换内容中的确切值一次。对于这个 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);

这是一种工作,它只用链接替换一次关键字,但如果关键字是复合的(本周),它被替换为这个星期,这是错误的......

感谢您的帮助...谢谢。

更新

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

4

3 回答 3

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数组来满足您的需求

于 2013-06-20T13:20:48.663 回答
1

罗伯特的答案有效,但取代了每一次出现,这不是必需的。在 preg 替换的末尾添加 ', 1' 只会将每个出现替换一次。

例如 echo preg_replace($patterns, $replacement, $content, 1);

于 2013-06-20T13:33:57.417 回答
1

如果您将使用某种“ID”而不是链接,在 preg_replace 中使用它,完成后,您可以调用 str_replace 并用真实链接替换 ​​ID?

$content = preg_replace('/'.$keyword.'/i', $IDS, ($content),1);
$content = str_replace($IDS, $link, $content);
于 2013-06-20T16:39:48.123 回答