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/
Pregunta duplicada; Ver en http://stackoverflow.com/questions/5282745/simple-wiki-parser-and-link-autodetection – Akarun
Posible duplicado de [Reemplazar URLs en texto con enlaces HTML] (http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links) – cweiske