Last active
December 7, 2019 00:02
-
-
Save stemar/a30f2255ae1b23c8ee6cc02d9f0091b3 to your computer and use it in GitHub Desktop.
PHP format() function with named placeholders
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 | |
| /** | |
| * Return a formatted string like vsprintf() with named placeholders. | |
| * | |
| * When a placeholder doesn't have a matching key in `$args`, | |
| * the placeholder is returned as is to see missing args. | |
| * @param string $string | |
| * @param array $kwargs | |
| * @param string $pattern | |
| * @return string | |
| */ | |
| function format($string, array $kwargs, $pattern='/\{\{(\w+)\}\}/') { | |
| return preg_replace_callback($pattern, function ($matches) use ($kwargs) { | |
| return @$kwargs[$matches[1]] ?: $matches[0]; | |
| }, $string); | |
| } |
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 | |
| echo format("Coordinates: {{latitude}}, {{longitude}}", ['latitude'=>'37.24N', 'longitude'=>'-115.81W']); | |
| // => Coordinates: 37.24N, -115.81W | |
| echo format("Coordinates: %{latitude}, %{longitude}", ['latitude'=>'37.24N', 'longitude'=>'-115.81W'], "/\%\{(\w+)\}/"); | |
| // => Coordinates: 37.24N, -115.81W | |
| echo format("Coordinates: :latitude, :longitude", ['latitude'=>'37.24N', 'longitude'=>'-115.81W'], "/:(\w+)/"); | |
| // => Coordinates: 37.24N, -115.81W | |
| echo format("Coordinates: {latitude}, {longitude}", ['latitude'=>'37.24N', 'longitude'=>'-115.81W'], "/\{(\w+)\}/"); | |
| // => Coordinates: 37.24N, -115.81W | |
| echo format("Coordinates: {{latitude}}, {{longitude}}, {{timezone}}", ['latitude'=>'37.24N', 'longitude'=>'-115.81W']); | |
| // => Coordinates: 37.24N, -115.81W, {{timezone}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment