2010-07-01 29 views
7

Esto es lo que no funciona para mí:Cadena de texto de límite PHP ¿NO incluye etiquetas html?

<?php 
$string = 'I have a dog and his name is <a href="http://www.jackismydog.com">Jack</a> and I love him very much because he\'s my favorite dog in the whole wide world and nothing could make me not love him, I think.'; 
$limited = substr($string, 0, 100).'...'; 
echo $string; 
?> 

que quieren limitar el texto visible a 100 caracteres, pero utilizando substr() también está incluido el texto no visible en el límite (<a href="http://www.jackismydog.com"> y </a>), que ocupa 41 de esos 100 caracteres disponibles.

¿Hay alguna forma de limitar el texto para que la palabra "Jack" del enlace se incluya en el límite, pero no <a href="http://www.jackismydog.com"> o </a>?

Editar: quiero seguir el enlace en la cadena, pero no contar con su longitud hacia el límite ..

Respuesta

4

Una función para truncar palabras en código HTML:

//+ Jonas Raoni Soares Silva 
//@ http://jsfromhell.com 
function truncate($text, $length, $suffix = '&hellip;', $isHTML = true) { 
    $i = 0; 
    $simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'meta'=>true); 
    $tags = array(); 
    if($isHTML){ 
     preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 
     foreach($m as $o){ 
      if($o[0][1] - $i >= $length) 
       break; 
      $t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1); 
      // test if the tag is unpaired, then we mustn't save them 
      if($t[0] != '/' && (!isset($simpleTags[$t]))) 
       $tags[] = $t; 
      elseif(end($tags) == substr($t, 1)) 
       array_pop($tags); 
      $i += $o[1][1] - $o[0][1]; 
     } 
    } 

    // output without closing tags 
    $output = substr($text, 0, $length = min(strlen($text), $length + $i)); 
    // closing tags 
    $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : ''); 

    // Find last space or HTML tag (solving problem with last space in HTML tag eg. <span class="new">) 
    $pos = (int)end(end(preg_split('/<.*>| /', $output, -1, PREG_SPLIT_OFFSET_CAPTURE))); 
    // Append closing tags to output 
    $output.=$output2; 

    // Get everything until last space 
    $one = substr($output, 0, $pos); 
    // Get the rest 
    $two = substr($output, $pos, (strlen($output) - $pos)); 
    // Extract all tags from the last bit 
    preg_match_all('/<(.*?)>/s', $two, $tags); 
    // Add suffix if needed 
    if (strlen($text) > $length) { $one .= $suffix; } 
    // Re-attach tags 
    $output = $one . implode($tags[0]); 

    //added to remove unnecessary closure 
    $output = str_replace('</!-->','',$output); 

    return $output; 
} 

Fuente: http://snippets.dzone.com/posts/show/7125

2

Si desea limitar la parte del texto, es necesario analizar y comprobar el límite mismo . La forma más sencilla es:

if (strlen(strip_tags($string)) > 100) 
{ 
    // the url inside $url is too big 
} 
else 
{ 
    // the url inside $url fits 
} 
+0

No olvide reemplazar 'strlen' con' mb_strlen' si el texto es multibyte. – machineaddict

2

No es fácil - se puede utilizar, por supuesto strip_tags para de-htmlise la cadena, pero aparte de eso no hay una solución fácil.

+0

¡Solución a mi problema! Gracias :) – yanike

3

La manera más fácil sería analizar esto en una estructura DOM. Puede usar DOMDocument para eso. Luego, simplemente puede examinar los elementos y realizar cualquier cambio en el contenido.

Otro enfoque sería realizar una búsqueda y reemplazo de expresiones regulares de dos pasos: primero use la expresión regular para buscar el contenido de las etiquetas, luego use la expresión regular para reemplazar los contenidos con contenidos abreviados. Esto se puede lograr con sus funciones habituales preg_ *.

1

Usted podría intentar esto, trabajaron para mí si no hay etiquetas están en cadena $ diferir tendrá un valor de 0 entrega $ stringsize su valor original de 100

<?php 
$string = 'I have a dog and his name is <a href="http://www.jackismydog.com">Jack</a> and I love him very much because he\'s my favorite dog in the whole wide world and nothing could make me not love him, I think.'; 

$stringall=strlen($string); 
$striphtml = strip_tags($string); 
$stringnohtml=strlen(striphtml); 
$differ=($stringall-$stringnohtml); 
$stringsize=($differ + 100); 
$limited = substr($string, 0, $stringsize).'...'; 
echo $limited; 
?> 
+0

$ stringnohtml = strlen (striphtml); debe ser $ stringnohtml = strlen ($ striphtml); – raison

Cuestiones relacionadas