Search code examples
phpreplaceplaceholder

Replace curly braced placeholders in a string with the corresponding value


My PHP script gets a JSON config file. In this case, $json->autowelcome is the string: Hello {user}, welcome!

I want PHP to interprete the {user} as $user. How can I do that?

// Answer to tickle every 5 seconds
if (time() - dataAPI::get($key) >= 5) {
    dataAPI::set($key, time());
    $bot->network->answerTickle($who);
    $name = $bot->users[$who]->getRegname();
    $bot->network->sendMessageAutoDetection($who, $bot->botData['ontickle'], 2,true);
}

Solution

  • I can suggest you to use str_replace. Easier way.

    Exemple:

    $string   = 'Hello {name}!';
    $search[] = '{id}';            $replace[] = $user->getID();
    $search[] = '{name}';          $replace[] = $user->getNick();
    $search[] = '{regname}';       $replace[] = $user->getRegname();
    return str_replace($search, $replace, $string);