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 (sincearray_chunkpreserves keys when the third parameter istrue). - 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
相关产品推荐
相关产品推荐

