Sometimes, we want to replace URLs in text with HTML links with PHP.
In this article, we’ll look at how to replace URLs in text with HTML links with PHP.
How to replace URLs in text with HTML links with PHP?
To replace URLs in text with HTML links with PHP, we can use the preg_replace
function.
For instance, we write
preg_replace(
"/(http[s]{0,1}\:\/\/\S{4,})\s{0,}/ims",
'<a href="$1" target="_blank">$1</a> ',
$text_msg
);
to call preg_replace
with a regex that matches URLs in the $text_msg
string.
Then we get the URLs and put them in as the value of the href
attribute and the link text by putting '$1'
in the string in the 2nd argument.
The string with the replacements done is returned.
Conclusion
To replace URLs in text with HTML links with PHP, we can use the preg_replace
function.