函数 str_split() 不“识别”单词。以下是 str_split() 的一个“识别单词”的改编版本。
<?php
$array = str_split_word_aware(
'In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.',
32
);
var_dump($array);
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
if ($maxLengthOfLine <= 0) {
throw new RuntimeException(sprintf('The function %s() must have a max length of line at least greater than one', __FUNCTION__));
}
$lines = [];
$words = explode(' ', $string);
$currentLine = '';
$lineAccumulator = '';
foreach ($words as $currentWord) {
$currentWordWithSpace = sprintf('%s ', $currentWord);
$lineAccumulator .= $currentWordWithSpace;
if (strlen($lineAccumulator) < $maxLengthOfLine) {
$currentLine = $lineAccumulator;
continue;
}
$lines[] = $currentLine;
$currentLine = $currentWordWithSpace;
$lineAccumulator = $currentWordWithSpace;
}
if ($currentLine !== '') {
$lines[] = $currentLine;
}
return $lines;
}
?>
输出
<?php
array(5) {
[0]=> string(29) "In the beginning God created "
[1]=> string(30) "the heaven and the earth. And "
[2]=> string(28) "the earth was without form, "
[3]=> string(27) "and void; and darkness was "
[4]=> string(27) "upon the face of the deep. "
}
?>