<?php
function tagify($str, $baseUrl = '/board/')
{
$baseUrl = rtrim($baseUrl, '/');
return preg_replace('/
(?!<a[^<>]*>[^\#]*) # Dont match if there is an opening <a> tag and any chars after it.
\#([-_\w]+\b) # Match the hashtag.
(?![^<]*<\/a>) # Ignore any anding </a> tag including any chars before it not in hashtag.
/ix', '<a href="'.$baseUrl.'/$1">#$1</a>', $str);
}
$str = <<<STR
This is <a href="http://foo.com">This is #foo</a>.
Simple #html-stuff text <a href="http://foobar.com#baz">#simple</a>
<span class="simple">simple #simple text text</span>
STR;
echo tagify($str);