Php 让preg_match_在newline停止拍摄?
考虑以下示例,其中我尝试获取“原始”电子邮件地址:Php 让preg_match_在newline停止拍摄?,php,regex,Php,Regex,考虑以下示例,其中我尝试获取“原始”电子邮件地址: <?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> '; //~ pre
<?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";
?>
。。。但是,正如您所看到的,匹配[0][0]实际上包含换行符和下一行的“To:
”
那么,我怎样才能让preg\u match\u all
stop-captures在行尾
子问题:为什么我必须在
$matches[0]
和$matches[1]
中使用相同的结果集?我是否可以忽略$matches[1]
,然后继续处理$matches[0]
?只需将字符类中的空格替换为\s
。因此,这将不匹配任何空格字符,包括换行符
preg_match_all('/([^\s<]*@[^\s>,$]*)/m', $tststr, $matches);
char类中的$
将匹配文本$
符号。不,好像不在队伍的尽头。我们不需要在否定的char类中包含\n
,因为\s
完成了这项工作
preg_match_all('/[^\s<]*@[^\s>,]*/', $tststr, $matches);
preg_match_all('/[^\s,]*/',$tststr,$matches);
非常感谢@AvinashRaj——这很有效;删除捕获组括号也会删除$matches[1]
集。我还认为不再需要[^\s>,$]*
中的$
,因为我认为它将是匹配换行符的符号。再次感谢-干杯!你不是指文字$
?然后将其从角色类中删除$
在char类中会失去它的意义(匹配行尾边界)
preg_match_all('/[^\s<]*@[^\s>,$]*/', $tststr, $matches);
preg_match_all('/[^\s<]*@[^\s>,]*/', $tststr, $matches);