Converting URLs to links with PHP

While trying to read user timelines from the Twitter API, I found out that the tweets are only available in plain text. Of course, it is nicer (and more usable) if URLs are actually displayed as links. With a little use of regular expressions, this can easily be done.

But if you have long URLs and are displaying tweets in a relatively narrow column, this leads to a problem. Your tweets can have large gaps, depending how your browser puts line breaks in URLs. Some browsers break on slashes, some on dashes, on both or not at all. So I wrote a small function in PHP to add zero width breaks to links. Because I want to determine how links break and not leave it up to some random browser.


function linkify($str) {
    return preg_replace_callback('@(https?://)(\S+)@smu', 'linkify_callback', $str);
}

function linkify_callback($matches)
{
    $title = str_replace(
        array('/', '.', '-'),
        array('/​','.​', '-​'),
        $matches[2]);

    return '<a href="' . $matches[1] . $matches[2] . '">' . $matches[1] . $title . '</a>';
}

And in case you are wondering. Yes, I do not like to use URL shorteners.