- preg_replace: documentation ( source)
<?php
$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>
<span>foo #simple"onclick="alert('hi')" another
STR;
echo preg_replace('/(?!<a[^<>]*>[^#]+)#(\b[-_\w]+\b)(?![^<]*<\/a>)/', '<a href="/tags/$1">#$1</a>', $str);