Forum Moderators: coopster

Message Too Old, No Replies

Create html links and shorten link text

inking of text URLs

         

eltreno

12:30 am on Aug 20, 2009 (gmt 0)

10+ Year Member



Hi,

Found this preg_replace which links the urls within a block of text and works great.

preg_replace( "/(?<!<a href=\")((http)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\">\\0</a>", $text );

My problem is I want to be able to shorten the length of the actual viewable text link, so if a URL is very long I can still link it but the text that is shown (clickable) will be shortened to x characters.

So for example the text:
Go to my url, [this_is_a_very_long_url_that_will_stretch_my_html_column.com...] for more info

Will turn into something like:
Go to my url, <a href="http://thisisaverylongurlthatwillstretchmyhtmlcolumn.com">http://this_is_a_very...</a> for more info

Any ideas would be much appreciated.
Thanks

eltreno

12:40 am on Aug 20, 2009 (gmt 0)

10+ Year Member



Note: the 'webmasterworld' is linking the link in the first example text above, I will be parsing standard text not already linked text.

eelixduppy

3:59 am on Aug 20, 2009 (gmt 0)



You are going to have to use preg_replace_callback [us2.php.net] to do something like that. Just check the length of the replacement string and see if it is too long. If it is, truncate it then return the new version.

Give it a go and see what you can come up with.

eltreno

5:46 pm on Aug 20, 2009 (gmt 0)

10+ Year Member



Luvely dubley - came up with this
Works great on some brief testing


/* EXAMPLE TEXT TO SEARCH THROUGH */
$text = 'Here is some example text with 3 separate domain possibilities: www.example.com and http://www.example.com?param=1&param2=2 also [example.com,...] using max link text length at 25 characters';
echo '<p><strong>Before</strong>: '.$text.'</p>';


define('DISPLAY_URL_MAX_LENGTH',25);
$pattern = '¬(https?://¦www)([-A-Z0-9+&@#/%?=~_¦!:,.;]*[-A-Z0-9+&@#/%=~_¦])¬i';


$result = preg_replace_callback ( $pattern , 'create_link_and_shorten_link_text' , $text );
echo '<p><strong>AFTER</strong>: '.$result.'</p>';


/*
* CREATE LINK AND SHORTEN LINK TEXT FUNCTION
*
* create_link_and_shorten_link_text()
* check 'link text' length and shorten if too long
* add HTTP:// if it doesn't exist
*
*/


function create_link_and_shorten_link_text($matches){


/* FIRST CHECK WE HAVE HTTP AT START OF URL, IT'S NEEDED! */
if (stripos ( $matches[1] , 'http') === false ){


$url ='http://'.$matches[1].$matches[2];
$text_link ='http://'.$matches[1].$matches[2];


} else {


$url =$matches[1].$matches[2];
$text_link =$matches[1].$matches[2];


}


/* SECOND CHECK THAT URL IS NOT TOO LONG, ELSE SHORTEN */


if (strlen($text_link) > DISPLAY_URL_MAX_LENGTH ) {
$text_link = substr ( $text_link, 0, DISPLAY_URL_MAX_LENGTH ) . '...';
}


/* RETURN LINKED URL */
return '<a href="' . $url . '">' . $text_link . '</a>';


}