/ PHP

Previous Article

PHP function to find links in a string

Next Article

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], &quot;<a _blank="" href="\" target="\">&quot;.$urls_to_replace[$i].&quot;</a> &quot;, $str);
        }

        return $str;
    } else {
        return $str;
    }
}
Avatar of Clive Walkden

Clive Walkden

Latest Articles

Linux command line tools, installations etc

Linux

Terraform Installation

A quick installation guide for Terraform on Ubuntu 18.04

Bitcoin - Cryptocurrency not just for geeks

Bitcoin

RollerCoin Intro

An introduction to the RollerCoin site and how you can use it to mine your own coins

Magento 2 Blog Posts

Magento 2

Magento 2.4.x Writing to a Log File

How to log to information to a file in different Magento 2.4.x versions