Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active September 15, 2019 04:37
Show Gist options
  • Save stemar/5188809 to your computer and use it in GitHub Desktop.
Save stemar/5188809 to your computer and use it in GitHub Desktop.
A PHP function to create an <a> link and a callback to join HTML tag attributes.
<?php
function a($href, $text=NULL, $attributes=NULL) {
if (!isset($text))
$text = strpos((string)$href, 'mailto:') !== FALSE ? substr($href, 7) : $href;
$attributes = compact('href') + (array)$attributes;
return sprintf('<a%s>%s</a>', join_attributes($attributes), (string)$text);
}
function join_attributes($attributes) {
$attrs = array();
foreach ((array)$attributes as $key => $value)
if ($key === 'value' || !is_blank($value))
$attrs []= sprintf(' %s="%s"', $key, (string)$value);
return join($attrs);
}
function is_blank($value) {
return empty($value) && !is_numeric($value);
}
<?php
a('http://google.com', 'Google', array('title'=>'Search with Google', 'class'=>'no_underline'));
// => &lt;a href="http://google.com" title="Search with Google" class="no_underline"&gt;Google&lt;/a&gt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment