Issue
I need to develop a PHP functionality where I have an array and a maximum character count.
Return a collection of strings where each string element represents a line that contains as many words as possible, with the words in each line being concatenated with a single ‘-‘. The length of each string must not exceed the maximum character length per line.
Your function should take in the maximum characters per line and return a data structure representing all lines in the indicated max length.
Examples:
words1 = [ "The", "day", "began", "as", "still", "as", "the",
"night", "abruptly", "lighted", "with", "brilliant",
"flame" ]
wrapLines(words1, 13) "wrap words1 to line length 13" =>
[ "The-day-began",
"as-still-as",
"the-night",
"abruptly",
"lighted-with",
"brilliant",
"flame" ]
What I tried so far is:
foreach ($words1 as $i => $word) {
$a = '';
if($i!= 0 && strlen($a) <= $lineLength1_1){
$a = $a.'-'.$word;
} else {
$a = $word;
}
echo $a;
}
The result I get is.
The-day-began-as-still-as-the-night-abruptly-lighted-with-brilliant-flame
Can someone please help me how to check for the count based on condition and then break into next array key as result?
Thanks.
Solution
You can use PHP’s wordwrap()
function to help with this:
// $a is an array of strings, $line_length is the max line length
function wrap( $a, $line_length ) {
$r = array_map(
function($s) {
return str_replace( ' ', '-', $s ); // Replace spaces with dashes
},
// Rewrap $a by first joining it into a single string, then explode on newline chars into a new array
explode( "\n", wordwrap(join(' ', $a), $line_length ) )
);
return $r;
}
$words1 = [ "The", "day", "began", "as", "still", "as", "the",
"night", "abruptly", "lighted", "with", "brilliant",
"flame" ];
print_r( wrap( $words1, 13 ) );
Results:
Array
(
[0] => The-day-began
[1] => as-still-as
[2] => the-night
[3] => abruptly
[4] => lighted-with
[5] => brilliant
[6] => flame
)
Answered By – kmoser
Answer Checked By – Candace Johnson (BugsFixing Volunteer)