If we have 5 sentences in our content, and we want to split all text into two areas, we would use soemthing like:
$content = 'Sentence number one. Sentence number two. Sentence number 3. Sentence number 4. Sentence number 5.';
$slices = explode(" ", $content);
$first_slice = implode(" ", array_splice($slices, 0, 10));
$second_slice = implode(" ", array_splice($slices, 0));
echo '<div class="first_slice">'. $first_slice .'</div>';
echo '<div class="second_slice">'. $second_slice .'</div>';
Output of this is:
<div class="first_slice">Sentence number one. Sentence number two. Sentence number 3. Sentence</div>
<div class="second_slice">number 4. Sentence number 5.</div>
How to push started sentence to finish? In this example, how to get output:
<div class="first_slice">Sentence number one. Sentence number two. Sentence number 3. Sentence number 4.</div>
<div class="second_slice">Sentence number 5.</div>
CodePudding user response:
You're splitting by spaces, so it will split differently for data sets where the sentences have a variable number of spaces. Something like this will split by punctuation characters, and should work with a wider variety of inputs.
$content = 'Sentence number one! Sentence number two. Sentence number 3?
Sentence number 4. Sentence number 5!';
$slices = preg_split('/(?<=[.?!])\s /', $content, -1);
$first_slice = implode(" ", array_splice($slices, 0, 3));
$second_slice = implode(" ", array_splice($slices, 0));
echo '<div class="first_slice">'. $first_slice .'</div>';
echo '<div class="second_slice">'. $second_slice .'</div>';```
CodePudding user response:
You can split in sentences by presuming every sentence end with a point and a blank space.
<?php
$content = 'Sentence number one. Sentence number two. Sentence number 3. Sentence number 4. Sentence number 5.';
$sentences = explode(". ", $content);
$first_slice = array_slice($sentences, 0, 3);
$second_slice = array_slice($sentences, 3, 4);
?>
And then print the sentences that you want:
<div class="first_slice">
<?php
echo implode(" ", $first_slice);
?>
</div>
<div class="second_slice">
<?php
echo implode(" ", $second_slice);
?>
</div>