Shorten URL text automatically

Discussion in 'PHP' started by m0nkeymafia, Aug 18, 2008.

  1. #1
    Hello
    I currently parse text using a regex that converts all URLs into links automatically

    $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $text);
    Code (markup):
    However what I would like, is for the text to appear as something like this: http://www.domain.com.../help.html

    Basically making longer URLs output as shorter versions.
    Can anyone help me doing this in a nice clean way?

    Thanks
     
    m0nkeymafia, Aug 18, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    $text = /* text with URLs */;
    $text = preg_replace_callback('~https?://[^\s\r\n"\'<>\!]+~i', 'shorten_urls', $text);
    
    function shorten_urls(array $url)
    {
        $url_maxlen = 35; // Max length of the displayed URL.
    
        if (strlen($url[0]) > $url_maxlen)
        {
            $offset1 = ceil(0.65 * $url_maxlen) - 2;
            $offset2 = ceil(0.30 * $url_maxlen) - 1;
    
            $urltext = substr($url[0], 0, $offset1) . '...' . substr($url[0], -$offset2);
        }
        else
        {
            $urltext = $url;
        }
    
        return "<a href=\"{$url[0]}\" title=\"{$url[0]}\">{$urltext}</a>";
    }
    
    
    PHP:
    ... untested, but it might actually work. (If not, you get the hint!)


    Oh yes, and stop using these ugly ereg_* functions. They're deprecated and will be removed in PHP 6. Not to mention they're about 6 times slower than the preg_* functions.
     
    nico_swd, Aug 18, 2008 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    I can't edit my post above anymore, but there's a small typo:
    
    $urltext = $url;
    
    PHP:
    .... should read:
    
    $urltext = $url[0];
    
    PHP:
     
    nico_swd, Aug 19, 2008 IP
  4. m0nkeymafia

    m0nkeymafia Well-Known Member

    Messages:
    399
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    125
    #4
    Thanks Nico thats great!!
     
    m0nkeymafia, Sep 5, 2008 IP