我有一个值和链接的数组,并且只需要用链接替换内容中的确切值一次。对于这种情况,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 week),它被替换为this和week,这是错误的…
非常感谢你的帮助……谢谢。$link是问题-如果没有'http://' works fine…
如果您使用某种'ID'代替链接,在preg_replace中使用它,当这完成后,您可以调用str_replace并将ID替换为真正的链接?
$content = preg_replace('/'.$keyword.'/i', $IDS, ($content),1);
$content = str_replace($IDS, $link, $content);
我编写的示例代码替换了所有的值。我不知道你想用什么替换文本所以我输入sample text
$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
数组
Robert的回答是有效的,但是替换了每一个不需要的出现。在preg replace的末尾添加',1'只替换每个出现一次。
。Echo preg_replace($patterns, $replacement, $content, 1);