Created
June 13, 2012 15:34
-
-
Save akuzemchak/2924817 to your computer and use it in GitHub Desktop.
PHP string formatting function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
), '%'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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