Convert URLs within text string into clickable links in PHP

If you have text which contains one or more than one URL, then you may need to convert those into hyperlinks on the web page.

You may often find in different types of social media networks like Facebook if messages text or comment text contains a URL in the text, then it becomes clickable. You can also see this in Gmail message text that URLs are always clickable in the message text.

Well, you can do the same task in PHP. Here I am going to tell you how to convert URLs within a text string into clickable links in PHP. So this article is going to be so amazing.

PHP has an inbuilt function which is the preg_replace() function. The PHP preg_replace() function can find the pattern from a string and can replace it with another or modified string.

Using this special function, we can find URLs from text or string and then replace it with the HTML anchor tag that contains the URL as the target link.

In this way, we can convert URLs into clickable links while showing on the web page in PHP.

Now, it’s time to see the example code snippet. Below is the PHP code example that will replace each and every URL inside the text or string with clickable links:

<?php
$str = "http://170.187.134.184 is an amazing website where you can find tutorials on various types of programming languages. Visit http://170.187.134.184 regularly.";
$url_pattern = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';   
$str= preg_replace($url_pattern, '<a href="$0">$0</a>', $str);
echo $str;
?>

So what we did in the above PHP code?

Also, read:

Well, in our code we have defined the pattern in a variable and pass it into the preg_replace() function.

If you run our code, then you will see that all the URLs within the text are now clickable links on the page. It’s so amazing… Isn’t it? We just did it within a few lines of code.

I hope, you enjoyed the solution you find in this article and it is going to be helpful in your web development project.

Leave a Reply

Your email address will not be published. Required fields are marked *