Using PHP replace regex with regex

user1272589 picture user1272589 · Feb 26, 2014 · Viewed 68.3k times · Source

I want to replace hash tags in a string with the same hash tag, but after adding a link to it

Example:

$text = "any word here related to #English must #be replaced."

I want to replace each hashtag with

#English ---> <a href="bla bla">#English</a>
#be ---> <a href="bla bla">#be</a>

So the output should be like that:

$text = "any word here related to <a href="bla bla">#English</a> must <a href="bla bla">#be</a> replaced."

Answer

Nambi picture Nambi · Feb 26, 2014
$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.