Skip to content

Instantly share code, notes, and snippets.

@akuzemchak
Created June 13, 2012 15:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akuzemchak/2924817 to your computer and use it in GitHub Desktop.
Save akuzemchak/2924817 to your computer and use it in GitHub Desktop.
PHP string formatting function
<?php
include 'str_format.php';
// example 1
echo str_format(':foo + :bar = :baz', array(
'foo' => 5,
'bar' => 6,
'baz' => 11,
));
// example 2
// repeated keys
echo str_format(':foo + :foo = :bar', array(
'foo' => 3,
'bar' => 6,
));
// example 3
// numbered keys
echo str_format(':0 + :1 = :2', array(
5,
6,
11,
));
// example 4
// custom prefix
echo str_format('%foo + %bar = %baz', array(
'foo' => 5,
'bar' => 6,
'baz' => 11,
), '%');
<?php
function str_format($subject, $replacements, $prefix = ':')
{
foreach($replacements as $key => $value)
{
$subject = str_replace($prefix.$key, $value, $subject);
}
return $subject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment