How to make URL inside text clickable link using PHP?

By Faruque Ahamed Mollick

Several times we may need to check for URL and need them to make clickable. We all see that thing on many websites that the URL inside a text block become clickable.

For example, when we send an email to someone and write just a plain text containing an URL then the URL inside the plan text become clickable.

Now in this article, I am going to tell you how you can make URL inside a text block clickable in PHP.

PHP code to make URL inside text block clickable link

Here is the PHP code is given below to convert URL inside a text block clickable link:

function url_to_clickable_link($plaintext) {
  return preg_replace(
  '%(https?|ftp)://([-A-Z0-9-./_*?&;=#]+)%i', 
  '<a target="blank" rel="nofollow" href="$0" target="_blank">$0</a>', $plaintext);
}

In the above code, I have created a function url_to_clickable_link. Inside the function, I have used the inbuilt PHP function preg_replace which replace the URL inside the text block clickable. preg_replace Perform a regular expression search and replace. This function is introduced since PHP 4.0.4.

preg_replace has many important roles and real life application. Here in this tutorial, we have used this special PHP function to replace URL inside text block clickable.

Now let’s continue with our tutorial.

Below is the complete PHP code which you can test on your server. You can text it on XAMPP or WAMP server on your PC.

<?php

$plaintext = "https://www.codespeedy.com is a programming and coding related blog. https://www.codespeedy.com has the secured formatted URL.<br/>ftp://testftp.com is a FTP URL. <br/> This tutorial showing you how to make the URL inside text block clickable.";
echo url_to_clickable_link($plaintext);
function url_to_clickable_link($plaintext) {
  return preg_replace(
  '%(https?|ftp)://([-A-Z0-9-./_*?&;=#]+)%i', 
  '<a target="blank" rel="nofollow" href="$0" target="_blank">$0</a>', $plaintext);
}

?>

Now that’s it. You can run the code. When you will run it, you will see the below result:

 

 

https://www.codespeedy.com is a programming and coding related blog. https://www.codespeedy.com has the secured formatted URL.
ftp://testftp.com is a FTP URL.
This tutorial showing you how to make the URL inside text block clickable.

 

So you can see that the code replacing all the URL text into <a href=”URL Text”>URL Text</a> format. Replacing is done by the PHP preg_replace function. Thus all the URL inside text block converted into a clickable link.

This is the magical power of the preg_replace function. We have successfully able to convert any URL inside text block clickable.

Leave a Reply

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