0

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 following...

foreach($users as $user) { 
$content = str_replace('{$name}', $user['name'], $content); 
$msg = '<div class="message">'.$content.'</div>'; 
}
Community
  • 1
  • 1
seoppc
  • 2,766
  • 7
  • 44
  • 76
  • do you have 20 identical rows in your $content variable? And poor users have to edit all 20 to set up a custom greeting? – Your Common Sense Feb 24 '11 at 13:59
  • you have {$name} as your value to search for. This is the same syntax as the inline variable insertion in PHP. could it be that {$name} gets translated to something wrong and hence the problem? try changing your macro to something simple like [name]. Or you can try to delimit '\{\$name\}' Also, we dont know what you are doing afterwards. You could just be overwriting $msg though then i guess it would only work for the last entry. – Ali Mar 08 '11 at 10:26

1 Answers1

-1

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

MattBelanger
  • 5,280
  • 6
  • 37
  • 34
  • @mabwi thanks for reply, can you please describe please what the problem was? thanks. – seoppc Feb 24 '11 at 13:53
  • You should stick to $content and not $new_content, and you should also remove $msg from the loop ;-) Btw, how does the author knows how many {$name} variables must be in $content??? Not really the right way to achieve this... – Capsule Feb 24 '11 at 13:53
  • Problem was, str_replace is "greedy" by default: it will replace all {$name} with the first $name. When you loop again, you don't have {$name} anymore because they were just all replaced in the previous step of the loop. – Capsule Feb 24 '11 at 13:54
  • Your code will not work because the fourth argument of str_replace must be passed by reference (must be a variable), but you can easily fix it with `$count = 1`. – Explosion Pills Feb 24 '11 at 14:18
  • who said you that $count limits anything? – Your Common Sense Feb 24 '11 at 16:12
  • @capsule we can't remove $msg from loop, as message have user email at bottom of mail, this system selects all emails from db and send posted message to those email with predefined basic email template. – seoppc Feb 24 '11 at 18:53