Foros del Web » Programando para Internet » PHP »

¿como convertir un texto en una url?

Estas en el tema de ¿como convertir un texto en una url? en el foro de PHP en Foros del Web. Buenas, como se puede poner por ejemplo www.forosdelweb.com y se convierta en <a href="www.forosdelweb.com"> www.forosdelweb.com </a> , he oido que es con esto: ----------------------------- <?php ...
  #1 (permalink)  
Antiguo 15/04/2003, 07:30
Avatar de Gryphus  
Fecha de Ingreso: febrero-2003
Ubicación: Spain
Mensajes: 216
Antigüedad: 21 años, 2 meses
Puntos: 0
¿como convertir un texto en una url?

Buenas, como se puede poner por ejemplo www.forosdelweb.com y se convierta en <a href="www.forosdelweb.com">www.forosdelweb.com</a> , he oido que es con esto:
-----------------------------
<?php $texto = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $texto); ?>
-----------------------------
pero no me va, hay algun error?? saludos y gracias

Última edición por Gryphus; 15/04/2003 a las 07:44
  #2 (permalink)  
Antiguo 15/04/2003, 08:35
Avatar de camargo  
Fecha de Ingreso: abril-2002
Ubicación: Kerétaro, Méjiko
Mensajes: 1.045
Antigüedad: 22 años
Puntos: 2
Código PHP:

    
echo "<a href=\"http://$valor\">$valor</a> 
__________________
http://www.chorcha.com
  #3 (permalink)  
Antiguo 15/04/2003, 09:19
Avatar de drcyber  
Fecha de Ingreso: julio-2002
Mensajes: 826
Antigüedad: 21 años, 8 meses
Puntos: 2
¿Cómo convertir la URL que esta en tu browser en un link para tu web?

Sencillo. Con la variable $PHP_SELF lo haces, juntandolo con lo que dijo camargo asi:

echo "<a href=\"$PHP_SELF\">$PHP_SELF</a>

Saludos !
__________________
Dr. Cyber
Ingeniarte.com
(soy el mismo Takitei)
  #4 (permalink)  
Antiguo 15/04/2003, 09:23
Avatar de Cain  
Fecha de Ingreso: enero-2002
Ubicación: Catalunya
Mensajes: 6.459
Antigüedad: 22 años, 3 meses
Puntos: 17
Me parece que lo que quieres es procesar un texto largo donde existen URL. Ejemplo:

"Oye, visita mi web en www.miweb.es que está muy bien".

Y que PHP lo convierta en:

"Oye, visita mi web en www.miweb.es que está muy bien".
__________________
M a l d i t o F r i k i
  #5 (permalink)  
Antiguo 15/04/2003, 11:21
 
Fecha de Ingreso: agosto-2002
Ubicación: Colón - Entre Rios - Argentina
Mensajes: 647
Antigüedad: 21 años, 8 meses
Puntos: 8
Esta funcion se usa en los foros phpBB, y se distribuye bajo licencia GNU.
Código PHP:
/**
 * Rewritten by Nathan Codding - Feb 6, 2001.
 * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
 *     to that URL
 * - Goes through the given string, and replaces [url]www.xxxx.yyyy[/url][zzzz] with an HTML <a> tag linking
 *     to [url]http://www.xxxx.yyyy[/url][/zzzz]
 * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
 *        to that email address
 * - Only matches these 2 patterns either after a space, or at the beginning of a line
 *
 * Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
 * have it require something like [email][email protected][/email] or such. We'll see.
 */
function make_clickable($text)
{

    
// pad it with a space so we can match things at the start of the 1st line.
    
$ret ' ' $text;

    
// matches an "xxxx://yyyy" URL at the start of a line, or after a space.
    // xxxx can only be alpha characters.
    // yyyy is anything up to the first space, newline, comma, double quote or <
    
$ret preg_replace("#([\t\r\n ])([a-z0-9]+?){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i"'\1<a href="\2://\3" target="_blank">\2://\3</a>'$ret);

    
// matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing
    // Must contain at least 2 dots. xxxx contains either alphanum, or "-"
    // zzzz is optional.. will contain everything up to the first space, newline, 
    // comma, double quote or <.
    
$ret preg_replace("#([\t\r\n ])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i"'\1<a href="http://\2.\3" target="_blank">\2.\3</a>'$ret);

    
// matches an email@domain type address at the start of a line, or after a space.
    // Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
    
$ret preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i""\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>"$ret);

    
// Remove our padding..
    
$ret substr($ret1);

    return(
$ret);

Te advierto que nunca la he usado, asi que no se si funciona
  #6 (permalink)  
Antiguo 15/04/2003, 11:29
 
Fecha de Ingreso: agosto-2002
Ubicación: Colón - Entre Rios - Argentina
Mensajes: 647
Antigüedad: 21 años, 8 meses
Puntos: 8
Ahora si lo probé y anda,
Código PHP:
$texto "Hola, esta es una pagina que me recomedo una amiga, http://www.microsoft.com, esta bastante buena (mi amiga)";
echo 
make_clickable($texto); 
Ta bueno el ejemplo !
  #7 (permalink)  
Antiguo 15/04/2003, 11:32
Avatar de Gryphus  
Fecha de Ingreso: febrero-2003
Ubicación: Spain
Mensajes: 216
Antigüedad: 21 años, 2 meses
Puntos: 0
emmm no va fran86 >__< lo pongo asi:
<?php
function make_clickable($text)
{
$ret = ' ' . $text;
$ret = preg_replace("#([\t\r\n ])([a-z0-9]+?){1}://([w-]+.([w-]+.)*[w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '1<a href="2://3" target="_blank">2://3</a>', $ret);
$ret = preg_replace("#([\t\r\n ])(www|ftp).(([w-]+.)*[w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '1<a href="http://2.3" target="_blank">2.3</a>', $ret);
$ret = preg_replace("#([\n ])([a-z0-9-_.]+?)@([w-]+.([w-.]+.)*[w]+)#i", "\1<a href=\"mailto:\2@\3\">\2@\3</a>", $ret);
$ret = substr($ret, 1);
return($ret);
$text = "Hola, esta es una pagina que me recomedo una amiga, http://www.microsoft.com, esta bastante buena (mi amiga)";
echo make_clickable($text);
}
?>

Última edición por Gryphus; 15/04/2003 a las 12:00
  #8 (permalink)  
Antiguo 15/04/2003, 13:13
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Hola a todos:

Perdonen que responda con una solución javascript, pero es tan sencilla que sería fácil implementarla ... es poner en javascript cadena_dirección.link(cadena_dirección)

ejemplo:
var cadena="http://www.caricatos.com";
document.write(cadena.link(cadena));

Saludos
  #9 (permalink)  
Antiguo 15/04/2003, 13:38
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Gryphus

Fijate bien como llamas a la función (¿conoces que es una función? ..) .. te lo digo porqué encerrastes en la función el ejemplo mismo de uso ...

Código PHP:
function make_clickable($text)
{
$ret ' ' $text;
$ret preg_replace("#([\t\r\n ])([a-z0-9]+?){1}://([w-]+.([w-]+.)*[w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i"'1<a href="2://3" target="_blank">2://3</a>'$ret);
$ret preg_replace("#([\t\r\n ])(www|ftp).(([w-]+.)*[w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i"'1<a href="http://2.3" target="_blank">2.3</a>'$ret);
$ret preg_replace("#([\n ])([a-z0-9-_.]+?)@([w-]+.([w-.]+.)*[w]+)#i""\1<a href=\"mailto:\2@\3\">\2@\3</a>"$ret);
$ret substr($ret1);
return(
$ret);
// aquí se acaba la función ..

// aquí va tu llamada a esa función ...
$text "Hola, esta es una pagina que me recomedo una amiga, [url]http://www.microsoft.com,[/url] esta bastante buena (mi amiga)";
echo 
make_clickable($text); 
Un saludo,
__________________
Por motivos personales ya no puedo estar con Uds. Fue grato haber compartido todos estos años. Igualmente los seguiré leyendo.
  #10 (permalink)  
Antiguo 15/04/2003, 13:42
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
mm caricatos ..

Pero la solución javascript .. si el URL está incrustado en una frase completa como la de los ejemplos .. el "invento" ya no funciona??¿?

Un saludo,
__________________
Por motivos personales ya no puedo estar con Uds. Fue grato haber compartido todos estos años. Igualmente los seguiré leyendo.
  #11 (permalink)  
Antiguo 15/04/2003, 16:34
Avatar de Gryphus  
Fecha de Ingreso: febrero-2003
Ubicación: Spain
Mensajes: 216
Antigüedad: 21 años, 2 meses
Puntos: 0
a ver si me explico, lo que yo quiero es poner un sistema de comentarios, que ya lo tengo, y luego cuando alguien`ponga un link que se le pueda dar directamente entendeis? es decir si por ejemplo pongo:
Hola soy Gryphus y esta es mi web: www.esta.com
que se convierta SOLO en:
Hola soy Gryphus y esta es mi web: www.esta.com
  #12 (permalink)  
Antiguo 15/04/2003, 16:55
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Gracias Cluster:

Como he dicho antes, es una solución fácil de implementar en javascript, pero la respuesta solo vale para cadenas completas.

Aún así, si te valiese la solución javascript, se podría convertir un texto en un array de palabras con el método split, y con indexOf se podría saber si se tratase de un enlace.

Aunque creo que con la potencia de php, se tienen que poder implementar estas cosas también...

Lo dicho... Perdón por la intromisión...

Un saludo
  #13 (permalink)  
Antiguo 15/04/2003, 18:17
 
Fecha de Ingreso: agosto-2002
Ubicación: Colón - Entre Rios - Argentina
Mensajes: 647
Antigüedad: 21 años, 8 meses
Puntos: 8
Gryphus, la funcion es la solucion a lo que requieres, pero la paso de nuevo (con los creditos del autor), porque ahora que me doy cuenta, usando el codigo vB de [ PHP ], imprime cualquier cosa y daba un error "Compilation failed: range out of order in character class at offset..."

/**
* Rewritten by Nathan Codding - Feb 6, 2001.
* - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
* to that URL
* - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
* to http://www.xxxx.yyyy[/zzzz]
* - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
* to that email address
* - Only matches these 2 patterns either after a space, or at the beginning of a line
*
* Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
* have it require something like [email protected] or such. We'll see.
*/
function make_clickable($text)
{

// pad it with a space so we can match things at the start of the 1st line.
$ret = ' ' . $text;

// matches an "xxxx://yyyy" URL at the start of a line, or after a space.
// xxxx can only be alpha characters.
// yyyy is anything up to the first space, newline, comma, double quote or <
$ret = preg_replace("#([\t\r\n ])([a-z0-9]+?){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="\2://\3" target="_blank">\2://\3</a>', $ret);

// matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing
// Must contain at least 2 dots. xxxx contains either alphanum, or "-"
// zzzz is optional.. will contain everything up to the first space, newline,
// comma, double quote or <.
$ret = preg_replace("#([\t\r\n ])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="http://\2.\3" target="_blank">\2.\3</a>', $ret);

// matches an email@domain type address at the start of a line, or after a space.
// Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
$ret = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);

// Remove our padding..
$ret = substr($ret, 1);

return($ret);
}
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 16:39.