Yep, something like that. You could even break it down more if you wanted, though we might be approaching some sort of point of diminishing returns at this point -- it all depends on the size/scope of your application and how much you might re-use these functions. I probably would not do this, but some people seem to like it.
<?php
define('DOMAIN', 'www.example.com');
function buildUrl($domain, $path, Array $params=null, $target=null)
{
$url = 'http://' . $domain . '/' . ltrim($path, '/');
if( ! empty($params)) {
$url .= '?';
foreach($params as $key => $value) {
$url .= urlencode($key) . '=' . urlencode($value) . '&';
}
$url = rtrim($url, '&');
}
if( ! empty($target)) {
$url .= '#' . urlencode($target);
}
return $url;
}
function htmlATag($url, $text, Array $attributes=null)
{
$html = '<a href="' . $url . '"';
if( ! empty($attributes)) {
foreach($attributes as $key => $value) {
$html .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
}
}
$html .= '>' . htmlspecialchars($text) . '</a>';
return $html;
}
?>
<!DOCTYPE html>
<head><title>Test</title></head>
<body>
<p><?php
echo htmlATag(
buildUrl(
DOMAIN,
'/foo/bar.php',
array(
'Hello' => 'World',
'this' => 'is a test'),
'some_id'
),
'The link text',
array(
'id' => 'an_id',
'class' => 'a_class'
)
);
?></p>
</body>
</html>
Output:
<!DOCTYPE html>
<head><title>Test</title></head>
<body>
<p><a href="http://example.com/foo/bar.php?Hello=World&this=is+a+test#some_id" id="an_id" class="a_class">The link text</a></p>
</body>
</html>