Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcus-at-localhost/97d00f7bbf2d5806d183a7ff5daaf7ce to your computer and use it in GitHub Desktop.
Save marcus-at-localhost/97d00f7bbf2d5806d183a7ff5daaf7ce to your computer and use it in GitHub Desktop.
Simple template string replacement with strstr.md

...instead of sprintf or str_replace1 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

  1. str_replaces searches through replacement again https://www.php.net/manual/en/function.strtr.php#117169

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment