$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
有什么主意吗?
答案 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()
。
参考:
答案 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