- urlencode: documentation ( source)
- preg_replace: documentation ( source)
<?php
$text = ' sdfsdaf sdafadsf #test sdfdsf';
$text = preg_replace('%(\A#(\w|(\p{L}\p{M}?)|-)+\b)|((?<=\s)#(\w|(\p{L}\p{M}?)|-)+\b)|((?<=\[)#.+?(?=\]))%u',
'<a class="hashtag" href="https://google.com/?q='.urlencode('$4').'" target="_blank">$4</a>', $text, 10);
echo ($text);