2009-06-24 23 views
5

Me pregunto si hay un fragmento simple que convierte los enlaces de cualquier tipo de análisis:PHP enlaces/correos electrónicos

http://www.cnn.com to <a href="http://www.cnn.com">http://www.cnn.com</a> 
cnn.com to <a href="http://www.cnn.com">cnn.com</a> 
www.cnn.com to <a href="http://www.cnn.com">www.cnn.com</a> 
[email protected] to to <a href="mailto:mailto:[email protected]">mailto:[email protected]</a> 

no quiero utilizar cualquier biblioteca específica PHP5.

Gracias por su tiempo.

ACTUALIZACIÓN He actualizado el texto anterior al que quiero convertirlo. Tenga en cuenta que la etiqueta href y el texto son diferentes para el caso 2 y 3.

UPDATE2 ¿Cómo lo hace el chat de Gmail? El suyo es bastante inteligente y funciona solo para nombres de dominios reales. p.ej. a.ly funciona, pero a.cb no funciona.

Respuesta

4

sí, http://www.gidforums.com/t-1816.html

<?php 
/** 
    NAME  : autolink() 
    VERSION  : 1.0 
    AUTHOR  : J de Silva 
    DESCRIPTION : returns VOID; handles converting 
       URLs into clickable links off a string. 
    TYPE  : functions 
    ======================================*/ 

function autolink(&$text, $target='_blank', $nofollow=true) 
{ 
    // grab anything that looks like a URL... 
    $urls = _autolink_find_URLS($text); 
    if(!empty($urls)) // i.e. there were some URLS found in the text 
    { 
    array_walk($urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow)); 
    $text = strtr($text, $urls); 
    } 
} 

function _autolink_find_URLS($text) 
{ 
    // build the patterns 
    $scheme   =  '(http:\/\/|https:\/\/)'; 
    $www   =  'www\.'; 
    $ip    =  '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; 
    $subdomain  =  '[-a-z0-9_]+\.'; 
    $name   =  '[a-z][-a-z0-9]+\.'; 
    $tld   =  '[a-z]+(\.[a-z]{2,2})?'; 
    $the_rest  =  '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';    
    $pattern  =  "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest"; 

    $pattern  =  '/'.$pattern.'/is'; 
    $c    =  preg_match_all($pattern, $text, $m); 
    unset($text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern); 
    if($c) 
    { 
    return(array_flip($m[0])); 
    } 
    return(array()); 
} 

function _autolink_create_html_tags(&$value, $key, $other=null) 
{ 
    $target = $nofollow = null; 
    if(is_array($other)) 
    { 
    $target  = ($other['target'] ? " target=\"$other[target]\"" : null); 
    // see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html 
    $nofollow = ($other['nofollow'] ? ' rel="nofollow"'   : null);  
    } 
    $value = "<a href=\"$key\"$target$nofollow>$key</a>"; 
} 

?> 
+0

no funciona demasiado bien. si escribo www.google.com, su enlace permanece como www.google.com en lugar de http://www.google.com. Además, solo google.com no funciona. –

+0

¿cómo lo puede hacer el chat de Gmail? –

+0

Creo que esto hace lo que quiere el asker. Simplemente no formateado EXACTAMENTE de la manera que él quiere. Él puede tener que modificar este código un poco. – Travis

-1

He aquí el fragmento de correo electrónico:

$email = "[email protected]"; 

$pos = strrpos($email, "@"); 
if (!$pos === false) { 
    // This is an email address! 
    $email .= "mailto:" . $email; 
} 

¿Qué es exactamente lo que busca que ver con los enlaces? tira el www o http? o agregue http://www a cualquier enlace si es necesario?

+0

añadir el http: // www, si es necesario a continuación, añadir la etiqueta a href les –

+0

He actualizado la cuestión. –

2

probar esto. (Para los enlaces no email)

$newTweet = preg_replace('!http://([a-zA-Z0-9./-]+[a-zA-Z0-9/-])!i', '<a href="\\0" target="_blank">\\0</a>', $tweet->text); 
+0

Trabajó excelente para mí, aunque necesitaba el "?" marca para trabajar tambiénAsí que utilicé: 'código' preg_replace ('! Http: // ([a-zA-Z0-9./-] + ([? =.] [A-z0-9_] +) *)! I ',' \\0 ', $ bla); – Leo

+0

debe haber https?: // para que los enlaces seguros también coincidan –

0

que sé es de 5 años de retraso, sin embargo, necesitan una solución similar y la mejor respuesta que obtuve fue por parte del usuario - erwan-dupeux-maire

respuesta

I escribe esta función Reemplaza todos los enlaces en una cadena. Los enlaces pueden estar en los siguientes formatos:

El segundo argumento es el objetivo para el enlace (' _blank ',' _top '... puede establecerse en falso). Creo que sirve ...

public static function makeLinks($str, $target='_blank') 
{ 
    if ($target) 
    { 
     $target = ' target="'.$target.'"'; 
    } 
    else 
    { 
     $target = ''; 
    } 
    // find and replace link 
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str); 
    // add "http://" if not set 
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str); 
    return $str; 
} 
Cuestiones relacionadas