将大文本拆分为可变数量的部分

时间:2019-03-11 15:11:54

标签: php arrays

$x = 4;
$story = "BUT I MUST EXPLAIN TO YOU HOW ALL THIS MISTAKEN IDEA OF DENOUNCING PLEASURE AND PRAISING PAIN WAS BORN AND I WILL GIVE YOU A COMPLETE ACCOUNT OF THE SYSTEM AND EXPOUND THE ACTUAL TEACHINGS OF THE GREAT EXPLORER";

我需要这样的东西:

$arr = explode(' 'nth($x), $story);

例如,如果$x == 4的每个元素都包含四个词:

BUT I MUST EXPLAIN TO YOU HOW ALL etc

如果$x == 5的每个元素将包含五个单词:

BUT I MUST EXPLAIN TO YOU HOW ALL THIS MISTAKEN etc

有什么主意吗?

2 个答案:

答案 0 :(得分:4)

您可以使用array_chunk()进行此操作:

<?php
    $x = 4;
    $story = "BUT I MUST EXPLAIN TO YOU HOW ALL THIS MISTAKEN IDEA OF DENOUNCING PLEASURE AND PRAISING PAIN WAS BORN AND I WILL GIVE YOU A COMPLETE ACCOUNT OF THE SYSTEM AND EXPOUND THE ACTUAL TEACHINGS OF THE GREAT EXPLORER";

    # we do a normal explode to get it into an array
    $arr = explode(' ', $story);
    # break into arrays divided by $x
    echo '<pre>'. print_r(array_chunk($arr, $x), 1) .'</pre>';

然后,您可以循环array_chunk数组并使用换行符回显-或implode()

参考:

https://secure.php.net/manual/en/function.array-chunk.php

答案 1 :(得分:0)

<?php
$story = "BUT I MUST EXPLAIN TO YOU HOW ALL THIS MISTAKEN IDEA OF DENOUNCING PLEASURE AND PRAISING PAIN WAS BORN AND I WILL GIVE YOU A COMPLETE ACCOUNT OF THE SYSTEM AND EXPOUND THE ACTUAL TEACHINGS OF THE GREAT EXPLORER";

foreach(
    array_chunk(
        str_word_count($story, 1),
        4 // Your chunk size.
    ) as $group
)
    echo implode(' ', $group), "\n";

输出:

BUT I MUST EXPLAIN
TO YOU HOW ALL
THIS MISTAKEN IDEA OF
DENOUNCING PLEASURE AND PRAISING
PAIN WAS BORN AND
I WILL GIVE YOU
A COMPLETE ACCOUNT OF
THE SYSTEM AND EXPOUND
THE ACTUAL TEACHINGS OF
THE GREAT EXPLORER