Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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