开发者

str_replace inside foreach loop

We are using str_replace to replace {$name} with $user['name'] from datebase, but its only replacing 1st entry of db, suppose there are 20 users, and 1st entry is 'tester' then it replace all {$name} with 1st entry only, check our code 开发者_StackOverflowfollowing...

foreach($users as $user) { 
$content = str_replace('{$name}', $user['name'], $content); 
$msg = '<div class="message">'.$content.'</div>'; 
}


If you only want to replace one occurrence, use the $count parameter on the function call

foreach($users as $user) { 
  $count = 1;
  $new_content = str_replace('{$name}', $user['name'], $content,$count); 
  $msg = '<div class="message">'.$new_content.'</div>'; 
}

Manual entry for str_replace

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜