2009-07-11 59 views
11

Si tengo una cadena que contiene una url (por ejemplo, la llamaremos $ url) como;PHP Eliminar URL de la cadena

$url = "Here is a funny site http://www.tunyurl.com/34934"; 

¿Cómo elimino la URL de la cadena? La dificultad es que las URL también pueden aparecer sin http: //, como;

$url = "Here is another funny site www.tinyurl.com/55555"; 

No hay HTML presente. ¿Cómo comenzaría una búsqueda si existiera http o www, luego elimine el texto/números/símbolos hasta el primer espacio?

+0

estamos hablando acerca de cómo extraer las direcciones URL de cuerdas o la eliminación de la enlace real en sí? $ url = "Aquí hay otro sitio divertido www.tinyurl.com/55555"; (extrayendo) $ url = "Aquí hay otro sitio divertido www.tinyurl.com/55555"; y $ someVar = 'www.tinyurl.com/55555'; (eliminación) $ url = "Aquí hay otro sitio divertido"; – tomzx

Respuesta

35

volví a leer la pregunta, aquí es una función que iba a funcionar como se pretendía:

function cleaner($url) { 
    $U = explode(' ',$url); 

    $W =array(); 
    foreach ($U as $k => $u) { 
    if (stristr($u,'http') || (count(explode('.',$u)) > 1)) { 
     unset($U[$k]); 
     return cleaner(implode(' ',$U)); 
    } 
    } 
    return implode(' ',$U); 
} 

$url = "Here is another funny site www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg"; 
echo "Cleaned: " . cleaner($url); 

Edición # 2/# 3 (debo ser aburrido). Aquí está una versión que verifica hay un dominio de nivel superior dentro de la URL:

function containsTLD($string) { 
    preg_match(
    "/(AC($|\/)|\.AD($|\/)|\.AE($|\/)|\.AERO($|\/)|\.AF($|\/)|\.AG($|\/)|\.AI($|\/)|\.AL($|\/)|\.AM($|\/)|\.AN($|\/)|\.AO($|\/)|\.AQ($|\/)|\.AR($|\/)|\.ARPA($|\/)|\.AS($|\/)|\.ASIA($|\/)|\.AT($|\/)|\.AU($|\/)|\.AW($|\/)|\.AX($|\/)|\.AZ($|\/)|\.BA($|\/)|\.BB($|\/)|\.BD($|\/)|\.BE($|\/)|\.BF($|\/)|\.BG($|\/)|\.BH($|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.TC($|\/)|\.TD($|\/)|\.TEL($|\/)|\.TF($|\/)|\.TG($|\/)|\.TH($|\/)|\.TJ($|\/)|\.TK($|\/)|\.TL($|\/)|\.TM($|\/)|\.TN($|\/)|\.TO($|\/)|\.TP($|\/)|\.TR($|\/)|\.TRAVEL($|\/)|\.TT($|\/)|\.TV($|\/)|\.TW($|\/)|\.TZ($|\/)|\.UA($|\/)|\.UG($|\/)|\.UK($|\/)|\.US($|\/)|\.UY($|\/)|\.UZ($|\/)|\.VA($|\/)|\.VC($|\/)|\.VE($|\/)|\.VG($|\/)|\.VI($|\/)|\.VN($|\/)|\.VU($|\/)|\.WF($|\/)|\.WS($|\/)|\.XN--0ZWM56D($|\/)|\.XN--11B5BS3A9AJ6G($|\/)|\.XN--80AKHBYKNJ4F($|\/)|\.XN--9T4B11YI5A($|\/)|\.XN--DEBA0AD($|\/)|\.XN--G6W251D($|\/)|\.XN--HGBK6AJ7F53BBA($|\/)|\.XN--HLCJ6AYA9ESC7A($|\/)|\.XN--JXALPDLP($|\/)|\.XN--KGBECHTV($|\/)|\.XN--ZCKZAH($|\/)|\.YE($|\/)|\.YT($|\/)|\.YU($|\/)|\.ZA($|\/)|\.ZM($|\/)|\.ZW)/i", 
    $string, 
    $M); 
    $has_tld = (count($M) > 0) ? true : false; 
    return $has_tld; 
} 

function cleaner($url) { 
    $U = explode(' ',$url); 

    $W =array(); 
    foreach ($U as $k => $u) { 
    if (stristr($u,".")) { //only preg_match if there is a dot  
     if (containsTLD($u) === true) { 
     unset($U[$k]); 
     return cleaner(implode(' ',$U)); 
    }  
    } 
    } 
    return implode(' ',$U); 
} 


$url = "Here is another funny site badurl.badone somesite.ca/worse.jpg but this badsite.com www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg"; 
echo "Cleaned: " . cleaner($url); 

rendimientos:

Cleaned: Here is another funny site badurl.badone but this and and 
+1

dulce! Me encanta copiar el código de pegar que simplemente funciona :) – GeoffreyF67

+0

Gracias por tomarse el tiempo para ampliar esto. – mrpatg

+0

¿Debería "este y" ser azul? No quiero editar el resultado real ;-) –

-1

Tendrá que escribir una expresión regular para extraer las URL.

3

análisis de texto para las direcciones URL es duro y buscando un pre-existente, el código probado en gran medida de que ya lo hace porque sería mejor que escribir su propio código y carecer de casos extremos. Por ejemplo, echaré un vistazo al proceso en Django's urlize, que ajusta las URL en los anclajes. Podría transferirlo a PHP y, en lugar de incluir las URL en un delimitador, simplemente elimínelas del texto.

6
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string); 
0

gracias micrófono,

actualización un poco, de retorno de error previo aviso,

'/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i'

$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);

0
$url = "Here is a funny site http://www.tunyurl.com/34934"; 
$replace = 'http www .com .org .net'; 
$with = ''; 

$clean_url = clean($url,$replace,$with); 
echo $clean_url; 

function clean($url,$replace,$with) { 

    $replace = explode(" ",$replace); 
    $new_string = ''; 
    $check = explode(" ",$url); 

    foreach($check AS $key => $value) { 
    foreach($replace AS $key2 => $value2) { 
     if (-1 < strpos(strtolower($value), strtolower($value2)) ) { 
      $value = $with; 
      break; 
     } 
    } 
    $new_string .= " ".$value; 
    } 
return $new_string; 
} 
+0

¿Podría proporcionar una explicación con su código? Podría ayudar más a OP o futuros usuarios. – Bono

Cuestiones relacionadas