2011-01-14 13 views
6

La mia variabile $content contiene il mio testo. Voglio creare un estratto da $content e visualizzare la prima frase e se la frase è più breve di 15 caratteri, vorrei visualizzare la seconda frase.PHP: ottieni le prime due frasi di un testo?

Ho già provato strippaggio primi 50 caratteri dal file, e funziona:

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

Ma io non sono felice con i risultati (non voglio nessuna parola da tagliare).

Esiste una funzione PHP che recuperi l'intero testo/frase, non solo il substrato?

Grazie mille!

+5

quello che è un cantare? –

+0

* (correlato) * [Troncare una stringa multibyte su n caratteri] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). La soluzione lì taglia rispetto ai confini delle parole. È un duplicato se non ti preoccupi delle frasi ma solo delle parole. – Gordon

+0

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

risposta

11

ho capito ed è stato abbastanza semplice però:

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

Interruzioni per" Mi chiamo Luka. Sono nato l'1.1.1953 a New York. " => "Mi chiamo Luka, sono nato 1." –

+1

@ TomášFejfar In tal caso, modifica '$ dot =". "' A '$ dot =". "' (Aggiungi uno spazio dopo il periodo) – NotJay

+0

Come nota a margine, se hai punti esclamativi che non vengono considerati per, puoi fare un 'str_replace' per sostituirli con punti. '$ content = str_replace ('!', '.', $ content);' – NotJay

6

C'è uno per le parole - wordwrap

codice di esempio:

<?php 

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

uscita:

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 per aggiungere collegamenti. –

+2

'wordwrap' non tronca le stringhe ma inserisce solo interruzioni di riga in una determinata posizione. 'mb_strimwidth' troncherebbe, ma non obbedisce ai limiti delle parole. – Gordon

+1

sì, hai ragione ... scusami per quello ... MA potresti fare qualcosa come substr ($ wrappedtext, 0, strpos ($ testo incartato, $ delimitatore) :) – Paul

1

Ecco una funzione modificata da un altro che ho trovato on-line; toglie qualsiasi HTML e pulisce alcuni caratteri MS funky prima; aggiunge quindi un carattere di ellissi facoltativo al contenuto per mostrare che è stato abbreviato. Si divide correttamente in una parola, quindi non avrai caratteri apparentemente casuali;

/** 
* 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; 
} 

ingresso:

<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,

uscita:

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

Molto bello. Funziona alla grande. Grazie per la condivisione. – ctown4life

2

Questo renderebbe sicuro che non ritornò mai una mezza parola,

$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 ('', array_shift (explode ('', substr ($ sommario, 500)))); ' Grazie – CrandellWS

+0

sebbene il mio commento sul codice non risolva la casella dovresti riuscire a evitarlo ... – CrandellWS

4

Ho scritto una funzione per fare qualcosa di simile a questo su uno dei nostri siti web. Sono sicuro che potrebbe essere ottimizzato per ottenere il risultato esatto da esso.

Fondamentalmente, gli si assegna una stringa di testo e la quantità di parole a cui si desidera assegnare. Quindi ridurrà a quella quantità di parole. Se l'ultima parola trovata non termina la frase, continuerà oltre la quantità di parole specificate fino a raggiungere la fine della frase. Spero che sia d'aiuto!

//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

Se fossi in te, io sceglierei di scegliere solo la prima 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 

Ciò semplificherebbe molto le cose.

6

Ecco un metodo di supporto rapido che ho scritto per ottenere le prime N frasi di un dato corpo di testo. Sono necessari punti, punti interrogativi e punti esclamativi e il valore predefinito è 2 frasi.

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

So che questo è un vecchio post ma cercavo la stessa cosa.

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

Per me il seguente lavorato:

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

Great one-liner –

Problemi correlati