2011-01-14 26 views
6

Moja zmienna $content zawiera mój tekst. Chcę utworzyć fragment z $content i wyświetlić pierwsze zdanie, a jeśli zdanie jest krótsze niż 15 znaków, chciałbym wyświetlić drugie zdanie.PHP - pierwsze dwa zdania tekstu?

Ja już próbowałem stripping pierwsze 50 znaków z pliku, a to działa:

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

Ale nie jestem zadowolony z rezultatów (nie chcę żadnych słów, aby być przecięte).

Czy istnieje funkcja PHP pobierająca całe wyrazy/zdania, a nie tylko substr?

Wielkie dzięki!

+5

Co to jest śpiewać? –

+0

* (powiązane) * [Obcięcie łańcucha wielobajtowego na n znaków] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). Rozwiązanie tam się tnie w odniesieniu do granic słów. To duplikat, jeśli nie interesują cię zdania, ale tylko słowa. – Gordon

+0

możliwy duplikat: http://stackoverflow.com/questions/79960/how-to- truncate-a-string-in-php-to-word-closest-to-a-ertain-number-of-charac – jasonbar

Odpowiedz

11

wyobraziłem go i to było całkiem proste mimo:

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

Przerwy dla" Nazywam się Luka. Urodziłem się 1.1.1953 w Nowym Jorku. " => "Nazywam się Luka, urodziłem się 1." –

+1

@ TomášFejfar W takim przypadku zmień '$ dot =". "' Na '$ dot =". "' (Dodaj spację po kropce) – NotJay

+0

Na marginesie, jeśli masz wykrzykniki, które nie są rozliczane dla, możesz zrobić 'str_replace', aby zastąpić je kropkami. '$ content = str_replace ('!', '.', $ content);' – NotJay

6

Jest jeden słowy - wordwrap

Przykład kodu:

<?php 

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

wyjściowa:

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 do dodawania linków. –

+2

'wordwrap' nie obcina łańcuchów, ale po prostu wstawia znaki linii w określonej pozycji. 'mb_strimwidth' będzie obcięte, ale nie przestrzega granic słów. – Gordon

+1

tak, masz rację ... przepraszam za to ... ALE możesz zrobić coś takiego, jak substr ($ tekst zawijany, 0, strpos ($ tekst zawijany, separator $)) :) – Paul

1

Oto funkcja modyfikowany kolejny znalazłem w Internecie; usuwa wszelkie HTML i oczyszcza niektóre funky znaków MS; następnie dodaje do treści opcjonalny znak wielokropka, aby pokazać, że zostało skrócone. Poprawnie dzieli się na słowo, więc nie będziesz miał pozornie przypadkowych znaków;

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

Wejście:

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

wyjściowa:

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

Bardzo ładne. Działa świetnie. Dziękuję za udostępnienie. – ctown4life

2

To już nigdy nie powrócił pół słowa;

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

'$ summary = implode ('', array_pop (eksploduje ('', substr ($ content, 0,500)));' '$ afterSummary = implode ('', array_shift (explode ('', substr ($ summary, 500)))); ' Dzięki – CrandellWS

+0

chociaż mój komentarz do kodu nie działa w polu, powinieneś być w stanie go skreślić ... – CrandellWS

4

Napisałem funkcję, aby zrobić coś podobnego na tej jednej z naszych stron internetowych. Jestem pewien, że można go poprawić, aby uzyskać dokładny wynik.

Zasadniczo podajesz ciąg tekstu i ilość słów, które chcesz przyciąć. Następnie przycina do tej liczby słów. Jeśli ostatnie słowo, które znajdzie, nie zakończy zdania, będzie ono kontynuowane w stosunku do liczby słów, które określiłeś, aż osiągnie koniec zdania. Mam nadzieję, że to pomoże!

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

Gdybym był tobą, to bym wybrać, aby wybrać tylko pierwsze zdanie.

$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 

To by po prostu wiele rzeczy.

6

Oto szybki sposób pomocnikiem, który napisałem, aby uzyskać pierwsze N zdań danej części tekstu. Bierze pod uwagę okresy, znaki zapytania i wykrzykniki i domyślnie przyjmuje 2 zdania.

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

Wiem, że to stary post, ale szukałem tego samego.

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

Dla mnie pracował następuje:

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

Świetna jedna linijka –

Powiązane problemy