Snippets

Javier Tapia Activar links dentro de un texto

Created by Javier Tapia
/**
 * activar_links
 * Identifica urls y direcciones de correo dentro de un texto y los transforma en etiquetas <a>
 **/
function activar_links($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)\.[^ \"\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=\"ftp://$3\" >$3</a>", $text);  
    $text = preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", 
        "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text); 
    // lo siguiente corrige la posición de las comas, que es un bug del parser anterior
    $text = str_replace(array(",</a>",",/</a>",", </a>",",/ </a>"),
                        array("</a>,","/</a>,","</a>,","/</a>,"),
                        $text);
    $text = str_replace(array('," >'), array('">'), $text);
    return $text;
}

// Ejemplo
$text = "Busca en www.google.com y me envías un mensaje a aa@uu.cl";
echo activar_links($text);
// Busca en <a href="http://www.google.com">www.google.com</a> y me envías un mensaje a <a href="mailto:aa@uu.cl">aa@uu.cl</a>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.