BigToach.com

PHP Snippets

parse_links

Information

(PHP Version >= 3.0.9)
Functions used in this snippet: ceil, preg_match_all, strlen, substr, preg_match, str_replace, preg_replace.

Description

str parse_links( str str[, int len[, str mid]] )

Adds around any links inside of a area of text. It works with [url], [url=site], and just plain http://site.com.

Snippet

<?php
function parse_links($str$len=25$mid='...'){
    
$left ceil(0.6666 $len);
    
$right $len $left;
    
preg_match_all('/(?<!=|\]|\/)((https?|ftps?|irc):\/\/|' '(www([0-9]{1,3})?|ftp)\.)([0-9a-z-]{1,25}' '[0-9a-z]{1}\.)([^\s&\[\{\}\]]+)/ims'$str$matches);
    foreach(
$matches[0] as $key=>$value){
        
$temp $value;
        if(
strlen($value) > ($len strlen($mid) + 2)){
            
$value substr($value0$left) . $mid substr($value,(-$right));
        }
        
$temp = !preg_match('/:\/\//'$temp) ? (substr($temp03) === 'ftp' 'ftp://' $temp 'http://' $temp) : $temp;
        
$temp $temp === $matches[0][$key] && $value === $matches[0][$key] ? '' '=' $temp;
        
$str str_replace($matches[0][$key],'[url' $temp ']' $value '[/url]'$str);
    }
    
$str preg_replace('/\[url=(?!http|ftp|irc)/ims''[url=http://'$str);
    
$str preg_replace('/\[url\](.+?)\[\/url\]/ims','<a href="$1" title="$1">$1</a>',$str);
    
$str preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/ims''<a href="$1" title="$1">$2</a>'$str);
    return 
$str;
}
?>

Example

parse_links Can be used in the following way:

<?php
echo parse_links('http://www.site.com'); 
// <a href="http://www.site.com">http://www.site.com</a>

echo parse_links('www.cropp.in'); 
// <a href="http://www.cropp.in">www.cropp.in</a>

echo parse_links('ftp://somesite.com');
// <a href="ftp://somesite.com">ftp://somesite.com</a>

echo parse_links('[url]www.cropp.in[/url]');
// <a href="http://www.cropp.in">www.cropp.in</a>

echo parse_links('[url=www.cropp.in]Cropp.in[/url]');
// <a href="http://www.cropp.in">Cropp.in</a>

echo parse_links'http://www.somesite.com/with/a/really/long/url/link' );
// <a href="http://www.somesite.com/with/a/really/long/url/link"> http://www.some...url/link</a>
?>

Added on Jul 6th at 1 am by Scott - 1 Comment
Updated on Jul 6th at 1 am.


1 Response to parse_links

ehcomunicacion commented on Jul 15th at 2 pm
Good function. Thanks!

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: