Clue Mediator

Find URLs in a string and make clickable links in PHP

📅December 29, 2020
🗁PHP

In this short article, we’ll discuss how to find URLs in a string and make clickable links in PHP. Sometimes you have data without any hyperlinks tags and when displayed on a web page you may need to convert the hyperlinks to our page.

As you can often see in Facebook and other social media networks, if there is a URL to the text of a message or comment, it becomes clickable. So here we will learn how to find a url in content and convert to anchor tag link using PHP.

Using built-in PHP function preg_replace(), we can easily find the URLs in text and make links in PHP. The `preg_replace()` function matches the pattern from string and replaces it with a defined modified string.

You can also check Find URLs in string and make a link using JavaScript.

Here, we take an example to find multiple URLs from a string and convert them to URLs automatically.

<!--?php
function makeUrltoLink($string) {
	// The Regular Expression filter
	$reg_pattern = "/(((http|https|ftp|ftps)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\:[0-9]+)?(\/\S*)?/";<p-->

	 // make the urls to hyperlinks
	return preg_replace($reg_pattern, '<a href="$0" target="_blank" rel="noopener noreferrer">$0</a>', $string);
}

$str = "Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.";

echo $convertedStr = makeUrltoLink($str);

// Output: Visit <a href="www.cluemediator.com" target="_blank" rel="noopener noreferrer">www.cluemediator.com</a> and subscribe us on <a href="https://www.cluemediator.com/subscribe" target="_blank" rel="noopener noreferrer">https://www.cluemediator.com/subscribe</a> for regular updates.
?>

In the above example, we have created a basic function that finds the pattern in a string and turns it into clickable links. It will find URLs that contain http, https, ftp, ftps or www.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂