Mohammad Saberi Mohammad Saberi - 1 year ago 123
PHP Question

Replace all URLs in text to clickable links in PHP

I have a web application written with PHP. I wanted to find all URLs inside users comments and change them to clickable links. I searched many websites and pages and found the solution below (Unfortunately I did not find its reference link again):

function convert($input) {
$pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
return $output = preg_replace($pattern, '<a href="http$2://$4">$0</a>', $input);

This code works perfectly thanks to its author. But I found out there is a bug in it that I could not solve.

If detected URL started with s letter (without https), the href value won't have that s character and http will change to https, whereas inner text is correct.

Example: >>
<a href=""></a>

Do you have any solution to solve this bug?

Answer Source
function convert($input) {
   $pattern = '@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download