简体   繁体   English

PHP preg_match正则表达式特殊模式

[英]php preg_match regex special pattern

I need to use preg_match to get some part of a string and use them later. 我需要使用preg_match来获取字符串的某些部分并在以后使用。 I'm not really good at using regex so, i hope you can help me with it. 我不太擅长使用正则表达式,所以希望您能为我提供帮助。

My current regex : 我当前的正则表达式:

$regex = '/(?P<name>\w+): (?P<agency>\w+)/';

My code so far: 到目前为止,我的代码:

$mail = imap_qprint(imap_body($mbox, $msgno)); 

$regex = '/(?P<name>\w+): (?P<agency>\w+)/';

preg_match($regex, $mail, $agency);
print_r($agency);

To keep it simple $mail looks like this (as an example): 为了简单起见,$ mail看起来像这样(例如):

Agency : Aname
Firstname : Fname
Lastname: Lname
Number of participant : 1

and i would like to get an array in $agency that can give me the Agency, First name and Last name, and with another regex (because i don't know if it's possible in only one) to get the number of participant. 我想在$ agency中获得一个数组,该数组可以为我提供代理,名字和姓氏以及另一个正则表达式(因为我不知道是否只有一个)可以获取参与者的数量。

Thanks in advance 提前致谢

With preg_match_all and (?P<name>.+)[:](?P<value>.+) you would get: 使用preg_match_all和(?P<name>.+)[:](?P<value>.+)您将得到:

$matches Array:
(
    [name] => Array
        (
            [0] => Agency 
            [1] => Firstname 
            [2] => Lastname
            [3] => Number of participant 
        )

    [value] => Array
        (
            [0] =>  Aname
            [1] =>  Fname
            [2] =>  Lname
            [3] =>  1

You could read these off as 您可以阅读这些作为

$data = array();
foreach($matches['name'] as $id => $name) {
    $data[$name] = trim($matches['value'][$id]);
}

Which would give you a key => value called $data with all the information. 这将为您提供一个包含所有信息的键=>值$ data。

EDIT: To make it a little more robust I would recommend using the multi-line flag and adding ^ and $ to your regex 编辑:为了使其更加健壮,我建议使用多行标志并将^和$添加到您的正则表达式中

preg_match_all('#^(?P<name>.+)[:](?P<value>.+)$#m',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);

怎么样: $regex = '/Agency\\s*:\\s*(\\w+).*?Firstname\\s*:\\s*(\\w+).*?Lastname:\\s*(\\w+).*?Number of participant\\s*:\\s*(\\d+)/s' : $regex = '/Agency\\s*:\\s*(\\w+).*?Firstname\\s*:\\s*(\\w+).*?Lastname:\\s*(\\w+).*?Number of participant\\s*:\\s*(\\d+)/s'$regex = '/Agency\\s*:\\s*(\\w+).*?Firstname\\s*:\\s*(\\w+).*?Lastname:\\s*(\\w+).*?Number of participant\\s*:\\s*(\\d+)/s'$regex = '/Agency\\s*:\\s*(\\w+).*?Firstname\\s*:\\s*(\\w+).*?Lastname:\\s*(\\w+).*?Number of participant\\s*:\\s*(\\d+)/s'

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

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