tags:

views:

51

answers:

3

I want to take data entered in this format:

John Smith
123 Fake Street
Fake City, 55555
http://website.com

and store the values in variables like so:

$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';

So first name will be whatever is entered on the first line address is whatever is on the second line city is whatever is entered on the third line before the comma seperator zip is whatever is on the third line after the comma and website is whatever is on the fifth line

I don't want the pattern rules to be stricter than that. Can someone please show how this can be done?

+3  A: 

Well, the regex would probably be something like:

([^\r]+)\r([^\r]+)\r([^,]+),\s+?([^\r]+)\r(.+)

Assuming that \r is your newline separator. Of course, it'd be even easier to use something like explode() to split things in to lines...

Dave DeLong
+3  A: 
$data = explode("\n", $input);

$name    = $data[0];
$address = $data[1];
$website = $data[3];

$place   = explode(',', $data[2]);

$city    = $place[0];
$zip     = $place[1];
toscho
+1 Clean and readable
Ravi Gummadi
and if you need some validation of the data (like website has proper syntax) then that's a good use of regex pattern on $website.
burkestar
A: 

If you want something more precise, you could use this:

$matches = array();

if (preg_match('/(?P<firstName>.*?)\\r(?P<streetAddress>.*?)\\r(?P<city>.*?)\\,\\s?(?P<zipCode>.*?)\\r(?P<website>.*)\\r/s', $subject, $matches)) {
   var_dump( $matches ); // will print an array with the parts
} else {
   throw new Exception( 'unable to parse data' );
}

cheers

JuanD