You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现从每组5句的文本中提取首句并合并展示求助

Solution to Extract First Sentences from Chunks

Here's how you can modify your code to extract the first sentence from each 5-sentence group and combine them into a single paragraph:

Step-by-Step Code Modification

First, store the chunked array in a variable instead of just printing it:

//Divide the text into equal parts containing 5 sentences each
$input_array = $result;
$chunks = array_chunk($input_array, 5, true); 
// print_r($chunks); // Optional: keep for debugging

Next, loop through each chunk to collect the first sentence of each group:

$firstSentences = [];
foreach ($chunks as $chunk) {
    // Get the first element of the chunk array
    $firstSentences[] = reset($chunk);
}

Finally, join these sentences into a single paragraph and display it:

$combinedParagraph = implode(' ', $firstSentences);
echo "<p>$combinedParagraph</p>";

Full Updated Code

//Reading file contents
$text = file_get_contents('majmunskikompjuter.txt'); 
// echo $text; // Optional: comment out if you don't need to display original text

//Divide the text into sentences
$result = preg_split('/(?<=[.?!;:])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
// print_r($result); // Optional: comment out if you don't need to display split sentences

//Divide the text into equal parts containing 5 sentences each
$input_array = $result;
$chunks = array_chunk($input_array, 5, true); 
// print_r($chunks); // Optional: comment out if you don't need to display chunks

//Select first sentence from each part and combine into a paragraph
$firstSentences = [];
foreach ($chunks as $chunk) {
    $firstSentences[] = reset($chunk);
}
$combinedParagraph = implode(' ', $firstSentences);
echo "<p>$combinedParagraph</p>";

Notes

  • The reset() function is used to get the first element of each chunk array, regardless of its key (since array_chunk preserves keys when the third parameter is true).
  • If you prefer to use array indexing instead, you can replace reset($chunk) with $chunk[array_key_first($chunk)] (requires PHP 7.3+).

内容的提问来源于stack exchange,提问作者TBV Translation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 23:28:08