2011-05-10 69 views
44

我如何從輸出中選擇前10個單詞?如何選擇一個句子的前10個單詞?

+0

你可能找到['s($ str) - > words(10)'](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d4 3adaa899642c1cce047e076dc/src/Str.php#L363)很有幫助,在[這個獨立的庫](https://github.com/delight-im/PHP-Str)中找到。 – caw 2016-07-27 00:43:50

回答

113
implode(' ', array_slice(explode(' ', $sentence), 0, 10)); 

要添加其他斷字像逗號和破折號支持,preg_match給出了一個快速的方法,並不需要分割字符串:

function get_words($sentence, $count = 10) { 
    preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches); 
    return $matches[0]; 
} 

由於Pebbl提到,PHP不能很好地處理UTF-8或Unicode,所以如果這是一個問題,那麼你可以用\w代替[^\s,\.;\?\!]\W[\s,\.;\?\!]

+0

這對我很好。我只需要顯示前5個句子,所以我將10切換到5,然後切換到''。 '在內爆並爆炸,它工作得很好。在顯示文本之後,我不得不放置一段時間,因爲最後一段時間被省略了。謝謝。 – NotJay 2013-11-21 18:19:02

+0

不錯的更新,+1避免分裂(和使用正則表達式!)。根據我更新的答案,您需要注意這些詞的界限。 – Pebbl 2015-04-02 23:34:03

+1

不幸的是,PHP仍然沒有想出如何處理Unicode - 感謝信息,我已經更新了我的答案。 – Kelly 2015-04-03 14:25:58

6

http://snipplr.com/view/8480/a-php-function-to-return-the-first-n-words-from-a-string/

function shorten_string($string, $wordsreturned) 
{ 
    $retval = $string; // Just in case of a problem 
    $array = explode(" ", $string); 
    /* Already short enough, return the whole thing*/ 
    if (count($array)<=$wordsreturned) 
    { 
     $retval = $string; 
    } 
    /* Need to chop of some words*/ 
    else 
    { 
     array_splice($array, $wordsreturned); 
     $retval = implode(" ", $array)." ..."; 
    } 
    return $retval; 
} 
48

如果在句子結構中存在意外的字符而不是空格,或者如果該句子包含多個連接空格,則簡單地在空格上分割將會不正確地運行。

無論您在單詞之間使用什麼樣的「空間」,都可以使用以下版本,並且可以輕鬆擴展以處理其他字符......它目前支持任何空格字符,還有。 ; ? !

function get_snippet($str, $wordCount = 10) { 
    return implode( 
    '', 
    array_slice( 
     preg_split(
     '/([\s,\.;\?\!]+)/', 
     $str, 
     $wordCount*2+1, 
     PREG_SPLIT_DELIM_CAPTURE 
    ), 
     0, 
     $wordCount*2-1 
    ) 
); 
} 

正則表達式是完美的這個問題,因爲你可以很容易地使代碼那樣靈活或嚴格的,只要你喜歡。但是你必須小心。我專門找到了上述針對詞語—之間的差距,而不是單詞本身—,因爲要明確定義一個詞的含義是相當困難的。

\w字邊界或其倒數\W。我很少依賴這些,主要是因爲—取決於您使用的軟件(如某些版本的PHP)— they don't always include UTF-8 or Unicode characters

在正則表達式中,最好是具體的,在任何時候。這樣你的表情可以處理之類的東西下面,無論身在何處,他們呈現:

echo get_snippet('Это не те дроиды, которые вы ищете', 5); 

/// outputs: Это не те дроиды, которые 

避免分裂可能是值得的。然而,在性能方面。所以你可以使用凱利的更新方法,但\w[^\s,\.;\?\!]+\W[\s,\.;\?\!]+。儘管我個人喜歡上面使用的分裂表達的簡單性,但它更易於閱讀並因此進行修改。但是,PHP函數的堆棧有點難看:)

+3

+1爲什麼這是0票?這是比其他答案更好的解決方案。雖然,人們不應該在PHP中使用駱駝案例。 – 2012-09-20 20:27:49

+0

@StephenSarcsamKamenar謝謝......並且好點,那天我一直在做太多javascripting :) – Pebbl 2012-10-13 10:23:22

+0

我同意@ StephenSarcsamKamenar的問題!我想這裏有兩個很多的答案。提出問題以更新正確答案是一項責任。這對我來說是最好的:毫無疑問,+1! – JeanValjean 2012-12-05 08:34:31

1

這可能對你有所幫助。函數返回N號。也就是說

public function getNWordsFromString($text,$numberOfWords = 6) 
{ 
    if($text != null) 
    { 
     $textArray = explode(" ", $text); 
     if(count($textArray) > $numberOfWords) 
     { 
      return implode(" ",array_slice($textArray, 0, $numberOfWords))."..."; 
     } 
     return $text; 
    } 
    return ""; 
    } 
} 
0

的,這是完全是我們正在尋找 只是削減ñ粘貼到你的程序並運行。

function shorten_string($string, $wordsreturned) 
/* Returns the first $wordsreturned out of $string. If string 
contains fewer words than $wordsreturned, the entire string 
is returned. 
*/ 
{ 
$retval = $string;  // Just in case of a problem 

$array = explode(" ", $string); 
if (count($array)<=$wordsreturned) 
/* Already short enough, return the whole thing 
*/ 
{ 
$retval = $string; 
} 
else 
/* Need to chop of some words 
*/ 
{ 
array_splice($array, $wordsreturned); 
$retval = implode(" ", $array)." ..."; 
} 
return $retval; 
} 

並調用你的代碼塊的功能就像

$data_itr = shorten_string($Itinerary,25); 
2

我建議使用str_word_count

<?php 
$str = "Lorem ipsum  dolor sit amet, 
     consectetur  adipiscing elit"; 
print_r(str_word_count($str, 1)); 
?> 

上面的例子將輸出:

Array 
(
    [0] => Lorem 
    [1] => ipsum 
    [2] => dolor 
    [3] => sit 
    [4] => amet 
    [5] => consectetur 
    [6] => adipiscing 
    [7] => elit 
) 

用途一個循環來獲取你想要的單詞。

來源:http://php.net/str_word_count

0

我做這種方式:

function trim_by_words($string, $word_count = 10) { 
    $string = explode(' ', $string); 
    if (empty($string) == false) { 
     $string = array_chunk($string, $word_count); 
     $string = $string[0]; 
    } 
    $string = implode(' ', $string); 
    return $string; 
} 

其UTF8兼容...

-4

我不知道爲什麼這一切混亂的,當有一個內置的Wordpress功能:

<?= wp_trim_words(get_the_content(), 15, '...') ?> 

回聲內容的前15個單詞(它在裏面工作一個常規循環)並添加省略號。

0

這可能對你有幫助。函數返回 no. of words

function num_of_word($text,$numb) { 
$wordsArray = explode(" ", $text); 
$parts = array_chunk($wordsArray, $numb); 

$final = implode(" ", $parts[0]); 

if(isset($parts[1])) 
    $final = $final." ..."; 
return $final; 
return; 
} 
echo num_of_word($text, 10); 
1

試試這個

$str = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.'; 
$arr = explode(" ", str_replace(",", ", ", $str)); 
for ($index = 0; $index < 10; $index++) { 
echo $arr[$index]. " "; 
} 

我知道這是不是時間來回答,而是讓新來的人選擇自己的答案。

0
function get_first_num_of_words($string, $num_of_words) 
    { 
     $string = preg_replace('/\s+/', ' ', trim($string)); 
     $words = explode(" ", $string); // an array 

     // if number of words you want to get is greater than number of words in the string 
     if ($num_of_words > count($words)) { 
      // then use number of words in the string 
      $num_of_words = count($words); 
     } 

     $new_string = ""; 
     for ($i = 0; $i < $num_of_words; $i++) { 
      $new_string .= $words[$i] . " "; 
     } 

     return trim($new_string); 
    } 

使用方法如下:

echo get_first_num_of_words("Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, illo?", 5); 

輸出:Lorem ipsum dolor sit amet

這個功能也可以非常好地Unicode字符像阿拉伯字符。

echo get_first_num_of_words("نموذج لنص عربي الغرض منه توضيح كيف يمكن استخلاص أول عدد معين من الكلمات الموجودة فى نص معين.", 100); 

輸出:نموذج لنص عربي الغرض منه توضيح كيف يمكن استخلاص أول عدد معين من الكلمات الموجودة فى نص معين.

2

要選擇給定文本的10個字,你可以下面的函數實現:使用

function first_words($text, $count=10) 
{ 
    $words = explode(' ', $text); 

    $result = ''; 
    for ($i = 0; $i < $count && isset($words[$i]); $i++) { 
     $result .= $words[$i]; 
    } 

    return $result; 
} 
2

這很容易做到str_word_count()

$first10words = implode(' ', array_slice(str_word_count($sentence,1), 0, 10)); 
+0

[鏈接到文檔](http://php.net/manual/en/function.str-word-count.php) – 2017-05-10 17:50:58

相關問題