简体   繁体   中英

Simple REGEX Question in PHP

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?

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...

$data = explode("\n", $input);

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

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

$city    = $place[0];
$zip     = $place[1];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM