Guy
Guy

Reputation: 317

Make urls clickable and shorten text

I have a string of text that is generated by users. I need to convert any urls in the text to a link (url) and in case the anchor text is long (the url) shorten it (very similar to how StackOverflow shortens anchors in url links).

I'm currently using this PHP code to convert the urls in the text to links:

return preg_replace(
        "/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i",
        "<a href=\"\\0\" target=\"blank\" rel=\"nofollow\">\\0</a>",$s);

Which seems to work for most urls I tested it on.

The problem is how do I shorten the anchor text if it's too long?

For example. this text:

Here is some text with a link http://www.google.com/search?q=bla%20bla%20bla that should be linkable. This url is short enough to show everything: http://bit.ly/blabla

Should be converted into this:

Here is some text with a link <a href="https://www.google.com/search?q=bla%20bla%20bla">https://www.google.com/search...</a> that should be linkable. 
This url is short enough to show everything: <a href="http://bit.ly/blabla">http://bit.ly/blabla</a>

Any ideas how I can manipulate the text in the regular expression match?

Upvotes: 0

Views: 738

Answers (1)

Steve H.
Steve H.

Reputation: 6947

One way is to put the URL text in a <span style="overflow:hidden; width: 75px;"> Note that you'll probably want to encodeURI() your link before inserting it in the DOM.

Upvotes: 1

Related Questions