简体   繁体   English

PHP中的简单REGEX问题

[英]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 因此,名字将是第一行中输入的名称,第二行中是城市的名称,逗号分隔符zip之前,第三行中将输入的内容,逗号和网站之后的第三行中,则是第三行中的内容。第五行

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. 假设\\r是您的换行符。 Of course, it'd be even easier to use something like explode() to split things in to lines... 当然,使用诸如explode()东西将内容分割成几行会更加容易...

$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 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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