'Splitting an address into up to 3 fields not exceeding 35 characters
I am using a UK postcode lookup service that returns data in varying field lengths depending on the address.
I must now submit this data to a third party API that sets a rather arbitrary character limit on field length of 35 characters.
I intend to continue storing the data in my local database in the format returned by the address lookup service so that if the user re-visits the site the address isn't in an unexpected format.
To send the data to the third party API I'll need to check the length of the three fields (address_1, address_2, address_3) and move content between the fields to ensure none exceed 35 characters.
So far I have got:
$address_fields[] = $order_data['billing_address_1'];
$address_fields[] = $order_data['billing_address_2'];
$address_fields[] = $order_data['billing_address_3'];
$parts = [];
foreach($address_fields as $key=>$line) {
$parts[] = array_filter(array_map('trim', explode(',', $line)));
}
$address = array_merge($parts[0], $parts[1], $parts[2]);
$address = implode(', ', $address);
Which gets me to a stage of having one string with the address data as entered split by commas. e.g.
string(95) "FAO: someone unimportant, grand union hotel, 7 sussex place, Side entrance, Westminster, London"
Ideally, I don't want to cut the address up in the middle of a word, and ideally at a comma or a space but this may not always be possible.
I feel like I'm likely overcomplicating my solution - any suggestions on the best approach to split a variable-length/content string like this into up to 3 35 character parts?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
