2011-01-14 16 views
6

Mi variable $content contiene mi texto. Quiero crear un extracto del $content y mostrar la primera oración y si la oración tiene menos de 15 caracteres, me gustaría mostrar la segunda oración.PHP: obtenga las dos primeras oraciones de un texto?

ya he intentado despojar primeros 50 caracteres del archivo, y funciona:

<?php echo substr($content, 0, 50); ?> 

Pero no estoy feliz con los resultados (no quiero palabras para ser cortados).

¿Hay una función PHP que obtenga todas las palabras/oraciones, no solo substr?

¡Muchas gracias!

+5

¿Qué es un cantar? –

+0

* (relacionado) * [Truncar una cadena multibyte a n caracteres] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). La solución allí corta con respecto a los límites de palabras. Es un duplicado si no te importan las oraciones, solo palabras. – Gordon

+0

posible duplicar: http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-charac – jasonbar

Respuesta

11

lo he descubierto y que era bastante simple sin embargo:

<?php 
    $content = "My name is Luka. I live on the second floor. I live upstairs from you. Yes I think you've seen me before. "; 
    $dot = "."; 

    $position = stripos ($content, $dot); //find first dot position 

    if($position) { //if there's a dot in our soruce text do 
     $offset = $position + 1; //prepare offset 
     $position2 = stripos ($content, $dot, $offset); //find second dot using offset 
     $first_two = substr($content, 0, $position2); //put two first sentences under $first_two 

     echo $first_two . '.'; //add a dot 
    } 

    else { //if there are no dots 
     //do nothing 
    } 
?> 
+7

Escapadas para" Mi nombre es Luka. Nací el 1.1.1953 en Nueva York. " => "Mi nombre es Luka. Nací 1". –

+1

@ TomášFejfar En ese caso, cambie '$ dot =". "' A '$ dot =". "' (Agregue un espacio después del período) – NotJay

+0

Como nota al margen, si tiene signos de exclamación que no están siendo contabilizados para, puedes hacer un 'str_replace' para reemplazarlos por puntos. '$ content = str_replace ('!', '.', $ content);' – NotJay

6

Hay uno para palabras - wordwrap

ejemplo de código:

<?php 

for ($i = 10; $i < 26; $i++) { 
    $wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i, "\n"); 
    echo substr($wrappedtext, 0, strpos($wrappedtext, "\n")) . "\n"; 
} 

Salida:

Lorem 
Lorem ipsum 
Lorem ipsum 
Lorem ipsum 
Lorem ipsum 
Lorem ipsum 
Lorem ipsum 
Lorem ipsum dolor 
Lorem ipsum dolor 
Lorem ipsum dolor 
Lorem ipsum dolor 
Lorem ipsum dolor sit 
Lorem ipsum dolor sit 
Lorem ipsum dolor sit 
Lorem ipsum dolor sit 
Lorem ipsum dolor sit 
+1

Ctrl + L para agregar enlaces. –

+2

'wordwrap' no trunca las cadenas sino que simplemente inserta saltos de línea en una posición determinada. 'mb_strimwidth' se truncaría, pero no obedecería los límites de las palabras. – Gordon

+1

sí, tienes razón ... lo siento por eso ... PERO podrías hacer algo como substr ($ wrappedtext, 0, strpos ($ wrappedtext, $ delimiter)) :) – Paul

1

He aquí una función modificada de otro he encontrado en Internet; elimina cualquier HTML y primero limpia algunos caracteres funky MS; luego agrega un carácter elíptico opcional al contenido para mostrar que se ha acortado. Se divide correctamente en una palabra, por lo que no tendrá caracteres aparentemente aleatorios;

/** 
* Function to ellipse-ify text to a specific length 
* 
* @param string $text The text to be ellipsified 
* @param int $max The maximum number of characters (to the word) that should be allowed 
* @param string $append The text to append to $text 
* @return string The shortened text 
* @author Brenley Dueck 
* @link http://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/ 
*/ 
function ellipsis($text, $max=100, $append='&hellip;') { 
    if (strlen($text) <= $max) return $text; 

    $replacements = array(
     '|<br /><br />|' => ' ', 
     '|&nbsp;|' => ' ', 
     '|&rsquo;|' => '\'', 
     '|&lsquo;|' => '\'', 
     '|&ldquo;|' => '"', 
     '|&rdquo;|' => '"', 
    ); 

    $patterns = array_keys($replacements); 
    $replacements = array_values($replacements); 


    $text = preg_replace($patterns, $replacements, $text); // convert double newlines to spaces 
    $text = strip_tags($text); // remove any html. we *only* want text 
    $out = substr($text, 0, $max); 
    if (strpos($text, ' ') === false) return $out.$append; 
    return preg_replace('/(\W)&(\W)/', '$1&amp;$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append; 
} 

de entrada:

<p class="body">The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What&rsquo;s in it for me?</p> <p>Kroger said the system, from Fujitsu,

Salida:

The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What's in it for me? Kroger said the …

+0

Muy agradable. Funciona muy bien. Gracias por compartir. – ctown4life

2

Esto se aseguraría de que nunca regresó a media palabra;

$short = substr($content, 0, 100); 
$short = explode(' ', $short); 
array_pop($short); 
$short = implode(' ', $short); 
print $short; 
+0

'$ summary = implode ('', array_pop (explode ('', substr ($ content, 0,500))));' '$ afterSummary = implode ('', desplazamiento_arreglo (explosión ('', substr ($ resumen, 500)))); ' Gracias – CrandellWS

+0

aunque mi comentario sobre el código no funciona, debería poder abreviarlo ... – CrandellWS

4

Escribí una función para hacer algo similar a esto en uno de nuestros sitios web. Estoy seguro de que podría modificarse para obtener su resultado exacto.

Básicamente, le da una cadena de texto y la cantidad de palabras que desea recortar. Luego se ajustará a esa cantidad de palabras. Si la última palabra que encuentra no termina la oración, continuará sobre la cantidad de palabras que especificó hasta que llegue al final de la oración. ¡Espero eso ayude!

//This function intelligently trims a body of text to a certain 
//number of words, but will not break a sentence. 
function smart_trim($string, $truncation) { 
    $matches = preg_split("/\s+/", $string); 
    $count = count($matches); 

    if($count > $truncation) { 
     //Grab the last word; we need to determine if 
     //it is the end of the sentence or not 
     $last_word = strip_tags($matches[$truncation-1]); 
     $lw_count = strlen($last_word); 

     //The last word in our truncation has a sentence ender 
     if($last_word[$lw_count-1] == "." || $last_word[$lw_count-1] == "?" || $last_word[$lw_count-1] == "!") { 
      for($i=$truncation;$i<$count;$i++) { 
       unset($matches[$i]); 
      } 

     //The last word in our truncation doesn't have a sentence ender, find the next one 
     } else { 
      //Check each word following the last word until 
      //we determine a sentence's ending 
      for($i=($truncation);$i<$count;$i++) { 
       if($ending_found != TRUE) { 
        $len = strlen(strip_tags($matches[$i])); 
        if($matches[$i][$len-1] == "." || $matches[$i][$len-1] == "?" || $matches[$i][$len-1] == "!") { 
         //Test to see if the next word starts with a capital 
         if($matches[$i+1][0] == strtoupper($matches[$i+1][0])) { 
          $ending_found = TRUE; 
         } 
        } 
       } else { 
        unset($matches[$i]); 
       } 
      } 
     } 

     //Check to make sure we still have a closing <p> tag at the end 
     $body = implode(' ', $matches); 
     if(substr($body, -4) != "</p>") { 
      $body = $body."</p>"; 
     } 

     return $body; 
    } else { 
     return $string; 
    } 
} 
-3

Si yo fuera usted, yo elegiría para recoger sólo la primera frase.

$t='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum justo eu leo.'; //input text 
$fp=explode('. ',$t); //first phrase 
echo $fp[0].'.'; //note I added the final ponctuation 

Esto simplemente simplificaría las cosas.

6

Aquí es un método de ayuda rápida que escribí para obtener los primeros N frases de una determinada masa de texto. Requiere puntos, signos de interrogación y signos de exclamación y tiene como valor predeterminado 2 oraciones.

function tease($body, $sentencesToDisplay = 2) { 
    $nakedBody = preg_replace('/\s+/',' ',strip_tags($body)); 
    $sentences = preg_split('/(\.|\?|\!)(\s)/',$nakedBody); 

    if (count($sentences) <= $sentencesToDisplay) 
     return $nakedBody; 

    $stopAt = 0; 
    foreach ($sentences as $i => $sentence) { 
     $stopAt += strlen($sentence); 

     if ($i >= $sentencesToDisplay - 1) 
      break; 
    } 

    $stopAt += ($sentencesToDisplay * 2); 
    return trim(substr($nakedBody, 0, $stopAt)); 
} 
3

Sé que esta es una publicación anterior pero estaba buscando lo mismo.

preg_match('/^([^.!?]*[\.!?]+){0,2}/', strip_tags($text), $abstract); 
echo $abstract[0]; 
2

Para mí Esta trabajaron:

$sentences = 2; 
echo implode('. ', array_slice(explode('.', $string), 0, $sentences)) . '.'; 
+0

Excelente diseño –

Cuestiones relacionadas