Php 字符串通过循环每次迭代替换为不同的值

Php string replace with different values each iteration through a loop

我为此搜索了答案,但找不到。抱歉,如果已经有一个了。这是我的问题:我在数据库中有一个名称列表。然后我有一条消息要显示给他们每个人。我想用字符串替换 -user- 的名称。这是我的代码:

$message = "Hello, -user-";
$getusers = mysql_query("SELECT * FROM users");
while ($row = mysql_fetch_array($getusers)){

    $username = $row["username"];

    //replace -user- with the actual username
    $message = str_replace("-user-", $username, $message);

    echo $username;
    echo $message;
}

现在假设我的数据库中有 3 个用户:dan、bob 和 jill。 这是它显示的内容:

dan Hello, dan bob Hello, dan jill Hello, dan.

我希望它显示的内容:

dan Hello, dan bob Hello, bob jill Hello, jill.

那你每次都要重新设置消息

$message = "Hello, -user-";

通过循环

移动

$message = "Hello, -user-";

进入 while 循环,每次都从相同的 $message 开始。否则只有第一个,"dan" 出现在第一次迭代和替换的消息中。