Using PHP replace regex with regex
This should nudge you in the right direction:
echo preg_replace_callback('/#(\w+)/', function($match) {
return sprintf('<a href="https://www.google.com?q=%s">%s</a>',
urlencode($match[1]),
htmlspecialchars($match[0])
);
}, htmlspecialchars($text));
See also: preg_replace_callback()
$input_lines="any word here related to #English must #be replaced.";
preg_replace("/(#\w+)/", "<a href='bla bla'>$1</a>", $input_lines);
DEMO
OUTPUT:
any word here related to <a href='bla bla'>#English</a> must <a href='bla bla'>#be</a> replaced.