简体   繁体   中英

php preg_match regex special pattern

I need to use preg_match to get some part of a string and use them later. 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):

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.

Thanks in advance

With preg_match_all and (?P<name>.+)[:](?P<value>.+) you would get:

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

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'

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