How to Linkfy all urls in text using php

posted on : Monday, 11 Mar, 2019

author avatar John Hashim

Hey! I’m a Junior web developer at PROTECHIG And founder of Unwrote Blog.

It is a good idea to convert all urls into links in your web application like contact form, comment forms, chat application etc. To find and replace all urls with their links we will use php preg_replace function. See below example

1
2
3
$text = "Hello Friends my website url is https://unwrote.com";
$text = preg_replace("\~\[[:alpha:]]+://\[^<>[:space:]]+\[[:alnum:]/]\~",'<a href="$0">$0</a>',$text);
echo $text;

this will always replace any link in comment box or in your email to out put this :

1
2
3
Output

Hello Friends my website url is https://unwrote.com