Skip to content

Instantly share code, notes, and snippets.

@tanakahisateru
Created February 7, 2017 10:41
Show Gist options
  • Select an option

  • Save tanakahisateru/f2639348cede833756117f1a72144482 to your computer and use it in GitHub Desktop.

Select an option

Save tanakahisateru/f2639348cede833756117f1a72144482 to your computer and use it in GitHub Desktop.
HTMLべんりツールこんな感じ?
<?php
/**
* Html static functions
*/
class Html
{
/**
* @param string $template
* @param array $values
* @return string
*/
public static function template($template, $values)
{
return preg_replace_callback('/\{\{\s*([A-Za-z0-9_]+?)\s*\}\}/', function ($m) use ($values) {
$name = $m[1];
if (isset($values[$name])) {
return $values[$name];
} else {
return $m[0];
}
}, $template);
}
/**
* @param string $tag
* @param array $attributes
* @param string $content
* @param bool $single
* @return string
*/
public static function tag($tag, $attributes, $content = null, $single = false)
{
$tag = strtolower($tag);
$as = [];
foreach ($attributes as $name => $value) {
if (is_bool($value)) {
if ($value === false) {
continue;
}
$value = $name;
} elseif (is_array($value)) {
// class / style like attributes
if (static::isArrayAssoc($value)) {
$avs = [];
foreach ($value as $k => $v) {
$avs[] = $k . ':' . $v;
}
$value = implode('; ', $avs);
} else {
$value = implode(' ', $value);
}
}
$as[] = $name . '=' . $value;
}
$ass = empty($as) ? '' : ' ' . implode(' ', $as);
$begin = "<{$tag}{$ass}>";
$end = "</{$tag}>";
if ($single) {
return $begin;
} elseif ($content) {
return $begin . $content . $end;
} else {
return $begin . $end;
}
}
/**
* @param string $tag
* @param array $attributes
* @return string
*/
public static function singleTag($tag, $attributes)
{
return static::tag($tag, $attributes, null, true);
}
/**
* @param array $array
* @return bool
*/
private static function isArrayAssoc($array)
{
foreach (array_keys($array) as $i => $k) {
if (is_integer($k) && $i != $k) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment