【问题标题】:Make preg_match_all stop capturing at newline?让 preg_match_all 在换行符处停止捕获?
【发布时间】: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";
?>

我认为正则表达式是这样工作的:

而且大多数情况下它都有效,结果是:

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]吗?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    只需将字符类中存在的空格替换为 \s 。因此这不会匹配任何空格字符,包括换行符。

    preg_match_all('/([^\s<]*@[^\s>,$]*)/m', $tststr, $matches);
    

    这可以进一步简化如下,即不需要使用捕获组和多行修饰符m

    preg_match_all('/[^\s<]*@[^\s>,$]*/', $tststr, $matches);
    

    DEMO

    $ 在 char 类中将匹配文字 $ 符号。不,它需要不结束。我们不需要在否定的 char 类中包含 \n,因为 \s 可以完成这项工作。

    preg_match_all('/[^\s<]*@[^\s>,]*/', $tststr, $matches);
    

    【讨论】:

    • 非常感谢@AvinashRaj - 这行得通;并且删除捕获组括号也会删除$matches[1] 集。我还认为 [^\s&gt;,$]* 中的 $ 不再需要,因为我认为它是匹配换行符的符号。再次感谢 - 干杯!
    • 你不是指文字$?然后将其从字符类中删除。 $ 在 char 类中会失去它的含义(匹配行边界的结尾)
    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多