Make text links clickable

The process of parsing text and making text links within it clickable is quite challenging, and well beyond the comprehension of my limited brain capacity.

Fortunately, there are plenty of people out there who have released their own snippets of code that tend to accomplish the task quite well – particularly if you’re submitting text from within a controlled platform (meaning that all the links are structured in a predictable way).

Joseph Scott, an employee of Automattic, is a bit of a coding guru and I make the pilgrimage to his site on a daily basis. He has made a PHP class from the WordPress make_clickable() function (in wp-includes/formatting.php).

I’ve used this class countless times. The code I’ve included below further turns each URL into a short URL using the TinyURL API. You could just about use any short URL service, including ours at fat.ly, or you could track each link with tracking code via appending an API key or some sort of authentication to the truncating URL.

You can download the standard code and the code that will truncate your links below.

 10) {
			$url = file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
			}

        return "{$matches[1]}{$url}";
    }

    public function cleanURL( $url ) {
        if( $url == '' ) {
            return $url;
        }

        $url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
        $url = str_replace( array( "%0d", "%0a" ), '', $url );
        $url = str_replace( ";//", "://", $url );

        /* If the URL doesn't appear to contain a scheme, we
         * presume it needs http:// appended (unless a relative
         * link starting with / or a php file).
         */
        if(
            strpos( $url, ":" ) === false
            && substr( $url, 0, 1 ) != "/"
            && !preg_match( "|^[a-z0-9-]+?.php|i", $url )
        ) {
            $url = "http://{$url}";
        }

        // Replace ampersans and single quotes
        $url = preg_replace( "|&([^#])(?![a-z]{2,8};)|", "&$1", $url );
        $url = str_replace( "'", "'", $url );

        return $url;
    }

    public function transform( $text ) {
        $text = " {$text}";

        $text = preg_replace_callback(
            '#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is',
            array( 'MakeItLink', '_link_www' ),
            $text
        );

        $text = preg_replace( '#(]+?>|>))]+?>([^>]+?)#i', "$1$3", $text );
        $text = trim( $text );

        return $text;
    }
}

$text = MakeItLink::transform( $mytext );
echo "$text";
?>


Download: Make text links clickable
Description: Parse text and make text links clickable.
Author:Internoetics
Category: PHP code
Date: January 9, 2010

If you liked this article, you may also like:

  1. PHP Function to Force Links to Open in a New Window
  2. PHP function to truncate text (into a preview or excerpt) with trailing dots…
  3. Automatically Convert MP3 links to Audio Players
  4. Break links into two halves separated by dots with PHP
  5. Calculate and highlight the differences between strings of text with PHP
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*