Reputation:
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
Upvotes: 0
Views: 133
Reputation: 37
How about:
$regex = '/Agency\s*:\s*(\w+).*?Firstname\s*:\s*(\w+).*?Lastname:\s*(\w+).*?Number of participant\s*:\s*(\d+)/s'
Upvotes: 0
Reputation: 14422
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);
Upvotes: 0