I have this string and i want to split it:
$string="2709 SW 29th St., Suite 100 Topeka, Kansas 66614";
I need to split it as: Zip =66614,state=Kansas,city=topeka,address2=Suite 100 ,address1=2709 SW 29th St. Thanks in advance.
Ok assuming a format like the following:
[address1], [address2] [city: single word], [state: word] [zip: numeric]
You'll need to explode
the string firstly by ,
and then by spaces and do some string checking. An example could be the following:
$string;
$a = explode(',', $string);
$address1 = trim($a[0]);
$b = explode(' ', trim($a[1]));
$city = array_pop($b);
$address2 = implode(' ', $b);
$c = explode(' ', trim($a[2]));
$zip = array_pop($c);
// check if $zip is numeric and valid
$state = implode(' ', $c);
Notice that trim
is used to remove optional spaces at the end and at the beginning of the string. The implode
function instead perform the reverse operation of explode
. And finally array_pop
treats and array like a stack and remove (returning it) the last element of the array.
This is just an example to get you started. Do not copy and paste this code. You should adapt it to your context and your real string format.