2011-01-14 26 views
6

Biến của tôi $content chứa văn bản của tôi. Tôi muốn tạo một đoạn trích từ $content và hiển thị câu đầu tiên và nếu câu ngắn hơn 15 ký tự, tôi muốn hiển thị câu thứ hai.PHP - nhận được hai câu đầu tiên của một văn bản?

Tôi đã cố gắng tước 50 ký tự đầu tiên từ tập tin, và nó hoạt động:

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

Nhưng tôi không hài lòng với kết quả (Tôi không muốn bất kỳ từ nào được cắt).

Có chức năng PHP nhận toàn bộ từ/câu, không chỉ nền?

Cảm ơn rất nhiều!

+5

một là gì hát? –

+0

* (liên quan) * [Cắt ngắn chuỗi đa thành chuỗi thành ký tự] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). Các giải pháp có cắt giảm đối với ranh giới từ. Đó là một bản sao nếu bạn không quan tâm đến các câu nhưng chỉ có các từ. – Gordon

+0

có thể trùng lặp: http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-charac – jasonbar

Trả lời

11

I figured it out và nó là khá đơn giản mặc dù:

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

Dấu ngắt cho" Tên tôi là Luka. Tôi sinh ra ở New York. 1.1.1953. " => "Tên tôi là Luka. Tôi sinh ra 1." –

+1

@ TomášFejfar Trong trường hợp đó, thay đổi '$ dot =". "' Thành '$ dot =". "' (Thêm dấu cách sau dấu chấm) – NotJay

+0

Như một lưu ý phụ, nếu bạn có dấu chấm than không được tính toán cho, bạn có thể làm một 'str_replace' để thay thế chúng bằng dấu chấm. '$ content = str_replace ('!', '.', $ content);' – NotJay

6

Có một cho lời - wordwrap

Ví dụ Code:

<?php 

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

Output:

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 để thêm liên kết. –

+2

'wordwrap' không cắt xén chuỗi nhưng chỉ chèn ngắt dòng tại một vị trí nhất định. 'mb_strimwidth' sẽ cắt ngắn, nhưng nó không tuân theo các ranh giới từ. – Gordon

+1

vâng, bạn đúng ... xin lỗi vì điều đó ... NHƯNG bạn có thể làm một cái gì đó như chất nền ($ wraptext, 0, strpos ($ wraptext, $ delimiter)) :) – Paul

1

Dưới đây là một chức năng biến đổi từ một tôi tìm thấy trực tuyến; nó loại bỏ bất kỳ HTML nào và làm sạch một số ký tự MS vui nhộn trước tiên; sau đó thêm một ký tự dấu chấm lửng tùy chọn vào nội dung để cho biết rằng nó được rút ngắn. Nó chia tách chính xác một từ, vì vậy bạn sẽ không có các ký tự dường như ngẫu nhiên;

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

Input:

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

Output:

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

Rất đẹp. Nó hoạt động tuyệt vời. Cám ơn vì đã chia sẻ. – ctown4life

2

này sẽ chắc chắn rằng nó không bao giờ quay trở lại một chữ nửa;

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

'$ summary = implode ('', array_pop (phát nổ ('', substr ($ content, 0,500))));' '$ afterSummary = implode ('', array_shift (phát nổ ('', substr ($ summary, 500)))); ' Cảm ơn – CrandellWS

+0

mặc dù nhận xét mã của tôi không hoạt động, bạn có thể rút ngắn nó ra ... – CrandellWS

4

Tôi đã viết một chức năng tương tự như vậy trên một trong các trang web của chúng tôi. Tôi chắc chắn rằng nó có thể được tinh chỉnh để có được kết quả chính xác của bạn ra khỏi nó.

Về cơ bản, bạn cung cấp cho nó một chuỗi văn bản và số lượng từ bạn muốn có nó. Sau đó nó sẽ cắt thành số lượng từ đó. Nếu từ cuối cùng nó tìm thấy không kết thúc câu, nó sẽ tiếp tục trên số lượng từ bạn đã chỉ định cho đến khi nó đạt đến cuối câu. Hy vọng nó giúp!

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

Nếu tôi là bạn, tôi muốn chọn chỉ câu đầu tiên.

$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 

Điều này rất đơn giản.

6

Dưới đây là một phương pháp helper nhanh chóng mà tôi đã viết để có được những N câu đầu tiên của một cơ thể nhất định của văn bản. Phải mất thời gian, dấu chấm hỏi và dấu chấm than để tính và mặc định là 2 câu.

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

Tôi biết đây là một bài đăng cũ nhưng tôi đang tìm kiếm một điều tương tự.

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

Đối với tôi, làm việc sau đây:

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

Tuyệt vời một lớp lót –

Các vấn đề liên quan