...instead of sprintf
or str_replace
1 in #php #string #template #pitfall
$strTemplate = "My name is :name, not :name2.";
$strParams = [
':name' => 'Dave',
'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
':name2' => 'Steve',
':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
];
echo strtr($strTemplate, $strParams);
// "My name is Dave, not Steve."
// replaced text gets searched again!
echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
// "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."
Footnotes
-
str_replaces
searches through replacement again https://www.php.net/manual/en/function.strtr.php#117169 ↩