Skip to content

Instantly share code, notes, and snippets.

@barnabywalters
Created December 5, 2013 12:28
Show Gist options
  • Save barnabywalters/7804428 to your computer and use it in GitHub Desktop.
Save barnabywalters/7804428 to your computer and use it in GitHub Desktop.
<?php
/**
* Given a string and a baseurl, finds all hashtags matching
* `#[\-_a-zA-Z0-9]+` and wraps them in an `a` element with `rel=tag` set
* and a `href` of baseurl + '/' + tagname without the #.
*/
function autolinkHashtags($text, $baseUrl) {
$baseUrl = rtrim($baseUrl, '/');
// $replacements = ["#tag" => "<a rel="tag" href="/tags/tag">#tag</a>]
$replacements = array();
$matches = array();
if (preg_match_all('/(?<=^|\s)\#([a-zA-Z0-9\-\_]+)/i', $text, $matches, PREG_PATTERN_ORDER)) {
// Look up #tags, get Full name and URL
foreach ($matches[0] as $name) {
$name = str_replace('#', '', $name);
$replacements[$name] = '<a rel="tag" href="' . $baseUrl . '/' . $name . '">#' . $name . '</a>';
}
// Replace #tags with valid microformat-enabled link
foreach ($replacements as $name => $replacement) {
$text = str_replace('#' . $name, $replacement, $text);
}
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment