3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php print_r(createAddressLines('block 717 #07-114 woodlands drive 70')); function createAddressLines($addressDetail) { $addressLines = [ 'addressLine1' => '', 'addressLine2' => '', 'addressLine3' => '' ]; if (35 >= strlen($addressDetail)) { $addressLines['addressLine1'] = $addressDetail; } else { $addressLineKeys = array_keys($addressLines); $lineIndex = 0; $addressWords = explode(' ', $addressDetail); print_r($addressWords); foreach ($addressWords as $addressWord) { $currentLine = $addressLines[$addressLineKeys[$lineIndex]]; // Doesn't Fit in Current Line if (35 < strlen($currentLine) + 1 + strlen($addressWord)) { // Case where a Word Itself Exceed 35 Characters if (35 <= strlen($addressWord)) { if (2 > $lineIndex) { $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . substr($addressWord, 0, 34 - strlen($addressLines[$addressLineKeys[$lineIndex]])); $lineIndex += 1; $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . substr($addressWord, 35 - strlen($addressLines[$addressLineKeys[$lineIndex]])); continue; } } // Last Word on Line 3 if ($lineIndex == 2) { $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . substr($addressWord, 0, 34 - strlen($addressLines[$addressLineKeys[$lineIndex]])); } // Go Next Line $lineIndex += 1; // Break if 3 Lines are Maxed if (3 <= $lineIndex) { break; } } $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . $addressWord; } } return (object) $addressLines; }
based on KXLeC
Output for 5.6.0 - 7.3.0alpha1
Array ( [0] => block [1] => 717 [2] => #07-114 [3] => woodlands [4] => drive [5] => 70 ) stdClass Object ( [addressLine1] => block 717 #07-114 woodlands drive [addressLine2] => 70 [addressLine3] => )