Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active December 7, 2019 00:02
Show Gist options
  • Select an option

  • Save stemar/a30f2255ae1b23c8ee6cc02d9f0091b3 to your computer and use it in GitHub Desktop.

Select an option

Save stemar/a30f2255ae1b23c8ee6cc02d9f0091b3 to your computer and use it in GitHub Desktop.
PHP format() function with named placeholders
<?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);
}
<?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