Created
January 8, 2020 11:02
-
-
Save sidouglas/94e2d4301029e0651a9cdeefc92d6fd1 to your computer and use it in GitHub Desktop.
Simple PHP Supplant Templating for HTML
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 | |
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