Convert plain text URLs into HTML hyperlinks in PHP

Volomike picture Volomike · Dec 25, 2009 · Viewed 92.9k times · Source

I have a simple commenting system where people can submit hyperlinks inside the plain text field. When I display these records back from the database and into the web page, what RegExp in PHP can I use to convert these links into HTML-type anchor links?

I don't want the algorithm to do this with any other kind of link, just http and https.

Answer

Rudder picture Rudder · Jan 11, 2016

Here is an other solution, This will catch all http/https/www and convert to clickable links.

$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 
$string = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

Alternatively for just catching http/https then use the code below.

$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';   
$string= preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

EDIT: The script below will catch all url types and convert them to clickable links.

$url = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

New update, If you're having the string strip the (s) then use the below code block, Thanks to @AndrewEllis for pointing this out.

$url = '@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

Here's a very simple solution for the URL not displaying correctly.

$email = '<a href="mailto:[email protected]">[email protected]</a>';
$string = $email;
echo $string;

It is a very simple fix but you will have to modify it for your own purpose.

I've provided multiple answers as some servers are setup differently, so one answer may work for some but not for others, but I hope the answer(s) work for you and if not then let me know and hopefully I can come up with another solution.

There are multiple scripts as some PHP files require different scripts also some servers are setup differently, Plus each have different requirements, Some want just HTTP/S, some want WWW and some want FTP/S, Each one will work depending on how the users own scripts are setup, I provided some text with each one with what they do.