Skip to content

Instantly share code, notes, and snippets.

@sidouglas
Created January 8, 2020 11:02
Show Gist options
  • Save sidouglas/94e2d4301029e0651a9cdeefc92d6fd1 to your computer and use it in GitHub Desktop.
Save sidouglas/94e2d4301029e0651a9cdeefc92d6fd1 to your computer and use it in GitHub Desktop.
Simple PHP Supplant Templating for HTML
<?php
trait TemplateTrait
{
/**
* supplant
* Replaces %tokens% inside a string with an array key/value
* strings not replaced are removed
* @param $string :string,
* @param $array :array
* @return string
*/
static public function supplant($string, $array)
{
$merged = array_merge(array_fill_keys(array_keys($array), ''), $array);
$keys = array_map(function ($key) {
return '%' . $key . '%';
}, array_keys($merged));
$return = str_replace($keys, $merged, $string);
return preg_replace('/%.*?(%)/', '', $return);
}
static public function html5_attributes($args)
{
$output = '';
foreach ($args as $key => $value) {
if (is_string($key)) {
if (!$value) {
continue;
}
$output .= $key . '="' . htmlspecialchars($value) . '" ';
} else {
$output .= $value . ' ';
}
}
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment