【发布时间】:2015-07-05 18:23:24
【问题描述】:
考虑这个例子,我尝试获取“原始”电子邮件地址:
<?php
$tststr = 'To: user1@example1.com
To: user2@example2.com, anotheruser3@example3.com
To: User <user4@example4.com>
To: User <user5@example5.com>, Another User <anotheruser6@example6.com>
';
//~ preg_match('/([^ <]*@[^ >,]*)/', $tststr, $matches); // no /g
preg_match_all('/([^ <]*@[^ >,$]*)/m', $tststr, $matches);
foreach ($matches as $key=>$val) {
//~ print("val [".$key."] = ". $val . "\n");
foreach ($val as $key1=>$val1) {
print("val [".$key."][".$key1."] = ". $val1 . "\n");
}
}
print "'".$matches[0][0]."'\n";
?>
我认为正则表达式是这样工作的:
-
[^ <]*- 选择不是 (^) 空格或尖括号<的字符序列 -
@- 选择@字符 -
[^ >,$]*- 选择不是 (^) 空格、尖括号<、逗号,或行尾$的字符序列 -
/m显然是 makes^and$match start/end of lines in addition to start/end of string
而且大多数情况下它都有效,结果是:
val [0][0] = user1@example1.com
To:
val [0][1] = user2@example2.com
val [0][2] = anotheruser3@example3.com
To:
val [0][3] = user4@example4.com
val [0][4] = user5@example5.com
val [0][5] = anotheruser6@example6.com
val [1][0] = user1@example1.com
To:
val [1][1] = user2@example2.com
val [1][2] = anotheruser3@example3.com
To:
val [1][3] = user4@example4.com
val [1][4] = user5@example5.com
val [1][5] = anotheruser6@example6.com
'user1@example1.com
To:'
...除了如您所见,匹配项 [0][0] 实际上包含换行符,以及下一行的“To:”!
那么,我怎样才能让preg_match_all 在行尾停止捕获?
子问题:为什么我必须在$matches[0] 和$matches[1] 中获得相同的结果集?我可以忽略$matches[1],直接处理$matches[0]吗?
【问题讨论】: