note 128219 added to function.str-split

From: Date: Tue, 14 Feb 2023 09:41:23 +0000
Subject: note 128219 added to function.str-split
Groups: php.notes 
Request: Send a blank email to php-notes+get-220175@lists.php.net to get a copy of this message
The function str_split() is not 'aware' of words. Here is an adaptation of str_split() that is 'word-aware'. <?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); /** * This function is similar to str_split() but this function keeps words intact; it never splits through a word. * * @return array<int, string> */ 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; // Overwrite the current line and accumulator with the current word $currentLine = $currentWordWithSpace; $lineAccumulator = $currentWordWithSpace; } if ($currentLine !== '') { $lines[] = $currentLine; } return $lines; } ?> OUTPUT: <?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. " } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.130 (proxied: 2a02:58:14d:5100:64f0:da34:94be:bca6) ---- Manual Page -- https://php.net/manual/en/function.str-split.php Edit -- https://main.php.net/note/edit/128219 Del: integrated -- https://main.php.net/note/delete/128219/integrated Del: useless -- https://main.php.net/note/delete/128219/useless Del: bad code -- https://main.php.net/note/delete/128219/bad+code Del: spam -- https://main.php.net/note/delete/128219/spam Del: non-english -- https://main.php.net/note/delete/128219/non-english Del: in docs -- https://main.php.net/note/delete/128219/in+docs Del: other reasons-- https://main.php.net/note/delete/128219 Reject -- https://main.php.net/note/reject/128219 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220175) next »