Foros del Web » Programando para Internet » PHP »

HTMLArea

Estas en el tema de HTMLArea en el foro de PHP en Foros del Web. Hola Estoy haciendo un formulario donde entre otros campos hay un textarea. Una vez que se rellena todo el formulario y pulsa enviar se visualizan ...
  #1 (permalink)  
Antiguo 25/10/2007, 08:57
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
HTMLArea

Hola

Estoy haciendo un formulario donde entre otros campos hay un textarea.
Una vez que se rellena todo el formulario y pulsa enviar se visualizan los datos que se han entrado.

Me gustaría que al escribir en ese textarea una dirección de internet (por ejemplo: www.doctordeseo.com) depues al visualizar esa dirección se convierta en un enlace, es decir, al pinchar sobre www.doctordeseo.con se cargue esa web.
Al igual que ocurre en este foro, yo escribo esa dirección de internet y cuando pulso a enviar mensaje aparece como un enlace. Sin necesidad de pinchar en Insertar Enlace.

¿cómo lo puedo hacer?
Gracias
  #2 (permalink)  
Antiguo 25/10/2007, 10:03
Avatar de Seppo  
Fecha de Ingreso: marzo-2005
Ubicación: Buenos Aires, Argentina
Mensajes: 1.284
Antigüedad: 19 años, 1 mes
Puntos: 17
Re: HTMLArea

En general, eso se hace con expresiones regulares.

Un ejemplo de cómo lo podés hacer

Código PHP:

<?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>";


?>
  #3 (permalink)  
Antiguo 27/10/2007, 01:23
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

Gracias.
El problema que me surge es que si utilizo eso cuando intento insertar por ejemplo una foto no me parece la foto sino el enlace a la foto.
  #4 (permalink)  
Antiguo 27/10/2007, 01:31
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

Cita:
Iniciado por trhipahx Ver Mensaje
Gracias.
El problema que me surge es que si utilizo eso cuando intento insertar por ejemplo una foto no me parece la foto sino el enlace a la foto.
El código que utilizo es :
<?php

if ( !defined( "_COMMON_PHP" ) ) return;

function format_body($body)
{

global $ForumAllowHTML, $plugins, $lQuote;

// get rid of moderator HTML tags
$body = str_replace('<HTML>', '', $body);
$body = str_replace('</HTML>', '', $body);

// replace all tag starts and ends
$body=str_replace('<', '&lt;', $body);
$body=str_replace('>', '&gt;', $body);

if(function_exists('preg_replace')){
// handle old legacy <> links by converting them into BB tags
$body=preg_replace("/&lt;((http|https|ftp):\/\/[a-z0-9;\/\?:@=\&\$\-_\.\+!*'\(\),~%#]+?)&gt;/i", "<a href=\"$1\" target=\"_blank\">$1</a>", $body);
$body=preg_replace("/&lt;mailto:([a-z0-9\-_\.\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+?)&gt;/i", "<a href=\"mailto:$1\">$1</a>", $body);
}

if(function_exists('preg_replace')){

if($ForumAllowHTML==1){
// replace url/link items
$body=preg_replace("/\[url\]((http|https|ftp|mailto):\/\/[a-z0-9;\/\?:@=\&\$\-_\.\+!*'\(\),~%#]+?)\[\/url\]/i", "<a href=\"$1\" target=\"_blank\">$1</a>", $body);
$body=preg_replace("/\[img\]((http|https|ftp):\/\/[a-z0-9;\/\?:@=\&\$\-_\.\+!*'\(\),~%]+?)\[\/img\]/i", "<img src=\"$1\" />", $body);
$body=preg_replace("/\[url=((http|https|ftp|mailto):\/\/[a-z0-9;\/\?:@=\&\$\-_\.\+!*'\(\),~%#]+?)\](.+?)\[\/url\]/i", "<a href=\"$1\" target=\"_blank\">$3</a>", $body);
$body=preg_replace("/\[email\]([a-z0-9\-_\.\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+?)\[\/email\]/i", "<a href=\"mailto:$1\">$1</a>", $body);



// replace simple tag replacements
$search=array(
"/\[(b)\]/",
"/\[\/(b)\]/",
"/\[(u)\]/",
"/\[\/(u)\]/",
"/\[(i)\]/",
"/\[\/(i)\]/",
"/\[(center)\]/",
"/\[\/(center)\]/",
"/\[(code)\]/",
"/\[\/(code)\]/",
"/\[(quote)\]/",
"/\[\/(quote)\]/",
"/\[(hr)\]/",
"/\[(s)\]/",
"/\[\/(s)\]/"
);

$replace=array(
'<strong>',
'</strong>',
'<u>',
'</u>',
'<i>',
'</i>',
'<center>',
'</center>',
'<pre>',
'</pre>',
"<blockquote>$lQuote:<br />\n",
'</blockquote>',
'<hr>',
'<strike>',
'</strike>'
);

$body=preg_replace($search, $replace, $body);
}



// clean up badly formed tags or if not allowed

$body=preg_replace("/\[url=.*?\]/", '', $body);


$search_clean=array(
"/\[url\]/",
"/\[\/url\]/",
"/\[img\]/",
"/\[\/img\]/",
"/\[email\]/",
"/\[email\]/",
"/\[\/email\]/"
);

$body=preg_replace($search_clean, '', $body);

}



// exec all read plugins
@reset($plugins['read_body']);
while(list($key,$val) = each($plugins['read_body'])) {
$body = $val($body);
}

$body=nl2br($body);
// fix for double-newlines in pre-tags
if(preg_match_all("/((<pre>).+?(<\/pre>))/is", $body, $matches)) {
foreach($matches[1] as $match) {
$clean=preg_replace("/(<br>\n|<br \/>\n)/i", "\n", $match);
$body=str_replace($match, $clean, $body);
}
}


return $body;

}

function validate_url($url)
{
// This function fixes invalid website addresses. It is not meant to be a definitive
// validator - all it tries to fix are links entered by a user who forgets to add 'http://'
// to the start of it.
// This function returns the fixed or unchanged URL
if (strlen(trim($url)) > 0) {
if (strtolower((substr($url,0,7)) == 'http://') || (strtolower(substr($url,0,8)) == 'https://')) {
$prepend = false; // user has entered a URL which seems OK
}
elseif ((substr($url,0,1) == '/') || (substr($url,0,2) == '\\')) {
$prepend = false; // user has entered a URL which could be a local address or maybe a computer on a LAN
}
elseif (substr($url,0,1) == '.') {
$prepend = false; // user has entered a URL which could be a relative address, eg "../"
}
elseif (strtolower(substr($url,0,7)) == 'file://'){
$prepend = false; // user has entered a valid file:// URL
}
else {
$prepend = true; // for all other address types we are going to assume the user forgot to add "http://"
}

if ($prepend) {
// add "http://" to URL - this will still work for IP addresses.
$url = 'http://' . $url;
}
}
return $url;
}

?>
  #5 (permalink)  
Antiguo 27/10/2007, 02:24
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

Tambien he encontrado esto:
¿alguien me puede ayudar a compilarlo?
Gracias

Tenía que resolver una necesidad que supongo que tienen muchas otras personas. Es, que los usuarios teclean texto que puede contener URLs, y estas URLs deben ser convertidas a enlaces. Otras condiciones eran que:

-La URL introducida podía después tener un intro, un tabulador, un espacio, o un paréntesis.
-Si la URL introducida pertenecía a un dominio externo al de la web en cuestión, éste debía abrirse en una nueva ventana, y si era una URL interna debía abrirse en la ventana actual.


Lo he resuelto así:
Código PHP: <?php
$texto = str_replace ( "\\r" , "" , $texto );

$texto = preg_replace ( "/(http:\\/\\/[^(\\)|[:space:])]*)\\)/" ,
"<a href=\\"\\\\1\\" target=\\"_blank\\">\\\\1</a>)" ,
$texto );

$texto = preg_replace ( "/(http:\\/\\/[^([:space:]|\\"|\\<)]*)[[:space:]]/" ,
"<a href=\\"\\\\1\\" target=\\"_blank\\">\\\\1</a> " ,
$texto );

$texto = preg_replace ( "/\\<a href=\\"(.*zonasiete.*)\\" target=\\"_blank\\"\\>/" ,
"<a href=\\"\\\\1\\">" ,
$texto );

?> En este caso, el dominio local es zonasiete.org. Espero que a alguien le sea útil. Por alguna extraña razón, no se muestra bien en mi post el code. Aclaraciones:

< ) -- ahí no hay un espacio, esos dos caracteres van seguidos.

\\1 -- Todos los unos (1) van precedidos de doble barra invertida, aunque solo se muestra una.
  #6 (permalink)  
Antiguo 29/10/2007, 01:12
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

He probado a meter el código del último mensaje intercalo en el código del mensaje anterior pero tampoco me ha funcionado.
  #7 (permalink)  
Antiguo 30/10/2007, 01:04
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

Agradecería cualquier ayuda con este tema.
  #8 (permalink)  
Antiguo 31/10/2007, 01:18
 
Fecha de Ingreso: septiembre-2006
Mensajes: 233
Antigüedad: 17 años, 6 meses
Puntos: 0
Re: HTMLArea

Un último intento.
Si nadie me contesta abandono y doy por hecho que lo que quiero hacer no se puede hacer.

Gracias a tod@s!!!

Un saludo
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.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:03.