3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php print_r(createAddressLines('10 TOH GUAN ROAD, The Furniture Mall Bldg. The Furniture Mall Bldg. 06-01')); function createAddressLines($addressDetail) { $addressLines = [ 'addressLine1' => '', 'addressLine2' => '', 'addressLine3' => '' ]; if (35 >= strlen($addressDetail)) { $addressLines['addressLine1'] = $addressDetail; } else { $addressLineKeys = array_keys($addressLines); $lineIndex = 0; $addressWords = explode(' ', $addressDetail); foreach ($addressWords as $addressWord) { // Doesn't Fit in Current Line if (35 < strlen($addressLines[$addressLineKeys[$lineIndex]]) + 1 + strlen($addressWord)) { // Case where a Word Itself Exceed 35 Characters if (35 <= strlen($addressWord)) { if (2 > $lineIndex) { $leftSpace = 35 - strlen($addressLines[$addressLineKeys[$lineIndex]]); $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . substr($addressWord, 0, $leftSpace); $lineIndex += 1; print_r('fdsa'.$lineIndex); $addressLines[$addressLineKeys[$lineIndex]] .= ' ' . substr($addressWord, $leftSpace, 35); 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 ZqaDT
Output for 5.6.0 - 7.3.0alpha1
stdClass Object ( [addressLine1] => 10 TOH GUAN ROAD, The Furniture [addressLine2] => Mall Bldg. The Furniture Mall [addressLine3] => Bldg. 06-01 )