E
E
eddasphp2015-09-22 19:27:36
PHP
eddasphp, 2015-09-22 19:27:36

how to split text into 5 parts php?

...
$seotext = $text;
...

there is a file with text - denoted by $text .
There are about 7-9 thousand words in the file.
How to split text into 5 parts? There are dots in the text. It is necessary that each new paragraph begins after a period.
And the paragraphs must fit in
paragraph 1
paragraph 2
paragraph 3
paragraph 4
paragraph 5

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2015-09-22
@eddasphp

If you want to get paragraphs of approximately the same size:

$text = '...';

$textSize = mb_strlen($text);
$paragraphsCount = 5;
$averageParagpaphSize = ceil($textSize / $paragraphsCount);

$paragraphs = [];

for ($i = 0; $i < $paragraphsCount; $i++)
{
  $currentParagraph = mb_substr($text, $averageParagpaphSize * $i, $averageParagpaphSize);
  $paragraphs[] = $currentParagraph;
}

for ($i = 1; $i < $paragraphsCount; $i++)
{
  $currentParagraph = $paragraphs[$i - 1];
  $nextParagraph = $paragraphs[$i];

  if (mb_substr($currentParagraph, -1, 1) !== '.')
  {
    $dotPosition = mb_strpos($nextParagraph, '.') + 1;

    $currentParagraph .= mb_substr($nextParagraph, 0, $dotPosition);
    $nextParagraph = trim(mb_substr($nextParagraph, $dotPosition));
  }

  $paragraphs[$i - 1] = $currentParagraph;
  $paragraphs[$i] = $nextParagraph;
}

var_dump($paragraphs);

The various edge cases are not handled here, but the general principle is clear.
Run
The much shorter option that Mikhail suggested :
$text = '...';
$paragraphsCount = 5;

$sentences = mb_split('\.', $text);
$paragraphs = array_chunk($sentences, ceil(count($sentences) / $paragraphsCount));

array_walk($paragraphs, function (&$paragraphSentences) {
  $paragraphSentences = implode(' ', $paragraphSentences);
});

var_dump($paragraphs);

Run
True, here in the paragraphs the same number of sentences is obtained, but in length they differ more.

M
Michael, 2015-09-22
@scherbuk

explode => array_chunk => implode

X
xmoonlight, 2015-09-22
@xmoonlight

explode()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question