[英]php preg_match regex special pattern
我需要使用preg_match來獲取字符串的某些部分並在以后使用。 我不太擅長使用正則表達式,所以希望您能為我提供幫助。
我當前的正則表達式:
$regex = '/(?P<name>\w+): (?P<agency>\w+)/';
到目前為止,我的代碼:
$mail = imap_qprint(imap_body($mbox, $msgno));
$regex = '/(?P<name>\w+): (?P<agency>\w+)/';
preg_match($regex, $mail, $agency);
print_r($agency);
為了簡單起見,$ mail看起來像這樣(例如):
Agency : Aname
Firstname : Fname
Lastname: Lname
Number of participant : 1
我想在$ agency中獲得一個數組,該數組可以為我提供代理,名字和姓氏以及另一個正則表達式(因為我不知道是否只有一個)可以獲取參與者的數量。
提前致謝
使用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
您可以閱讀這些作為
$data = array();
foreach($matches['name'] as $id => $name) {
$data[$name] = trim($matches['value'][$id]);
}
這將為您提供一個包含所有信息的鍵=>值$ data。
編輯:為了使其更加健壯,我建議使用多行標志並將^和$添加到您的正則表達式中
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.