2011-03-17 6 views
19

Quiero:mejor manera de hacer clic en enlaces en el bloque de texto

Here is link: http://google.com 
And http://example.com inside. 
And another one at the very end: http://test.net 

para convertirse en:

Here is link: <a href="http://google.com">http://google.com</a> 
And <a href="http://example.com">http://example.com</a> inside. 
And another one at the very end: <a href="http://test.net">http://test.net</a> 

parece una tarea trivial, pero no puedo encuentra una función de PHP que funcione. ¿Tienes alguna idea?

function make_links_clickable($text){ 
    // ??? 
} 

$text = 'Here is link: http://google.com 
And http://example.com inside. 
And another one at the very end: http://test.net'; 

echo make_links_clickable($text); 
+0

Pregunta duplicada; Ver en http://stackoverflow.com/questions/5282745/simple-wiki-parser-and-link-autodetection – Akarun

+0

Posible duplicado de [Reemplazar URLs en texto con enlaces HTML] (http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links) – cweiske

Respuesta

45

Utilice esta (funciona con FTP, HTTP, FTPS y HTTPS esquemas):

function make_links_clickable($text){ 
    return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text); 
} 
+0

¿Cuáles son los '!' Que colocó al principio y al final de la expresión regular? –

+0

! = El patrón (para reemplazar) "comienza con" ... – Akarun

+0

¿Cuáles son los caracteres que no son ASCII en su expresión regular? ('я' y 'Я') –

6

Pruebe algo como esto:

function make_links_clickable($text) 
{ 
    return preg_replace ('/http:\/\/[^\s]+/i', "<a href=\"${0}\">${0}</a>", $text); 
} 

$result = make_links_clickable($text); 
+1

y ¿qué pasa con XSS? –

+0

Las soluciones provistas en los enlaces sugeridos por Akarun y por Lawrence Cherone son más completas porque comprueban la URL de una url válida, detectan también enlaces https y ftp, urldecode enlaces antes de mostrarlos. Mi solución es más sucia, pero debería funcionar para tareas simples. –

5

usted debe referirse a esta respuesta Replace URLs in text with HTML links

+0

Y también consulte los siguientes recursos para obtener más información sobre "Vinculación" de URL (Sugerencia: hay un montón de "errores"): [El problema con las URL] (http://www.codinghorror.com/blog/2008/ 10/the-problem-with-urls.html "Por Jeff Atwood") y [Un patrón mejorado de Regex liberal y exacto para las URL coincidentes] (http://daringfireball.net/2010/07/improved_regex_for_matching_urls "Por John Gruber") y [Enlace de URL (HTTP/FTP)] (http://jmrware.com/articles/2010/linkifyurl/linkify.html "De verdad"). – ridgerunner

1

Inspirado por la respuesta de Akarun, se me ocurrió esta función para manejar todos los protocolos y enlaces que arte con la única www.

function make_links($text, $class='', $target='_blank'){ 
    return preg_replace('!((http\:\/\/|ftp\:\/\/|https\:\/\/)|www\.)([-a-zA-Zа-яА-Я0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?!ism', 
    '<a class="'.$class.'" href="//$3" target="'.$target.'">$1$3</a>', 
    $text); 
} 

Esta función tiene parámetros opcionales para añadir nombres de las clases en los enlaces y objetivo también opcional para el enlace, por lo que se abre en una nueva ventana/pestaña ... Por defecto, el parámetro se abre a nuevos enlaces ventana/pestaña, pero si no desea hacerlo, puede cambiar el valor predeterminado o cambiar el valor al llamar a la función.

2

Inspirado también por la respuesta de Akarun, la siguiente función solo dirigirá a los enlaces al texto que no sea ya un enlace. La funcionalidad añadida es la comprobación de que un enlace con el enlace de texto capturado aún no existe en la cadena de destino:

function make_links_from_http($content) { 
    // Links out of text links 
    preg_match_all('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i', $content, $matches); 
    foreach ($matches[0] as $key=>$link) { 
     if (!preg_match('!<a(.*)'.$link.'(.*)/a>!i', $content)) 
     { 
      $content = str_replace($link, '<a href="'.$link.'" target="_blank">'.$link.'</a>', $content); 
     } 
    } 

    return $content; 
} 

Por las pruebas, me di cuenta de que la función anterior falla en la línea # 5. Una función de "desordenado" que hace el trabajo es la siguiente:

function make_links_from_http($content) 
{ 
    // The link list 
    $links = array(); 

    // Links out of text links 
    preg_match_all('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i', $content, $matches); 
    foreach ($matches[0] as $key=>$link) 
    { 
     $links[$link] = $link; 
    } 

    // Get existing 
    preg_match_all('/<a\s[^>]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU', $content, $matches); 
    foreach ($matches[2] as $key=>$value) 
    { 
     if (isset($links[$value])) 
     { 
      unset($links[$value]); 
     } 
    } 

    // Replace in content 
    foreach ($links as $key=>$link) 
    { 
     $content = str_replace($link, '<a href="'.$link.'" target="_blank">'.$link.'</a>', $content); 
    } 

    return $content; 
} 

Para el nuevo código, he utilizado el tutorial en: http://www.the-art-of-web.com/php/parse-links/

2
function makeClickableLinks($text) 
{ 
$text = html_entity_decode($text); 
$text = " ".$text; 
$text= preg_replace("/(^|[\n ])([\w]*?)([\w]*?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text); 
$text= preg_replace("/(^|[\n ])([\w]*?)((www|wap)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text); 
$text= preg_replace("/(^|[\n ])([\w]*?)((ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"$4://$3\" >$3</a>", $text); 
$text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:[email protected]$3\">[email protected]$3</a>", $text); 
$text= preg_replace("/(^|[\n ])(mailto:[a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"[email protected]$3\">[email protected]$3</a>", $text); 
$text= preg_replace("/(^|[\n ])(skype:[^ \,\"\t\n\r<]*)/i", "$1<a href=\"$2\">$2</a>", $text); 
     return $text; 
} 

trabajo con:

www. example.com

https://www.example.com

http://www.example.com

wap.example.com

ftp.example.com

[email protected]

skype: ejemplo

mailto: usuario @ ejemplo.com

atherprotocol: //example.com

Cuestiones relacionadas