我有一组值和链接,并且只需要用链接替换内容中的确切值一次。对于这个 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://' 工作正常......现在这是个问题,如何逃避它......