This handy little function searches a string for urls and converts them into anchor tags. This is particularly useful for tweets pulled from Twitter using the API. This is used to prepare the links in my Twitter feed at the bottom of my site.
function make_links($str) {
$reg_ex_url = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$urls = array();
$urls_to_replace = array();
if (preg_match_all($reg_ex_url, $str, $urls)) {
$numOfMatches = count($urls[0]);
$url_count = 0;
for ($i=0; $i<$numOfMatches; $i++) {
$alreadyAdded = false;
$url_count = count($urls_to_replace);
for ($j=0; $j<$url_count; $j++) {
if ($urls_to_replace[$j] == $urls[0][$i]) {
$alreadyAdded = true;
}
}
if (!$alreadyAdded) {
array_push($urls_to_replace, $urls[0][$i]);
}
}
$url_count = count($urls_to_replace);
for ($i=0; $i<$url_count; $i++) {
$str = str_replace($urls_to_replace[$i], "<a _blank="" href="\" target="\">".$urls_to_replace[$i]."</a> ", $str);
}
return $str;
} else {
return $str;
}
} Clive Walkden
Posted:
Latest Articles
A Comprehensive Guide to Major Releases of Magento 2
Explore the evolution of Magento 2 through its major releases, detailing features added, popularity metrics, and issues encountered.
Clive Walkden
Author
Linux —
How to Install NordLayer VPN Client on Ubuntu 20.04 and Connect to a Virtual NetworkA simple to follow installation guide for NordLayer VPN
Clive Walkden
Author
MySQL —
Mastering MySQL Database Imports on LinuxLearn efficient ways to import MySQL databases on Linux using the mysql command-line client. Explore the --source option and < operator for seamless data migration. Master MySQL imports on Linux with our comprehensive guide.
Clive Walkden
Author