Regex在单词之间找到,但不要';t返回搜索词


Regex find between words, but don't return the search words

我正试图从电子邮件中获取主题

这项工作:

preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);

但回报是这样的:

"Subject:This is my subject!Date:"

我只想这是我的主题根据我所读到的,这就是我应该得到的。我错过了什么?

您可以使用subjects[1][0]以的形式访问值

$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
print_r($subjects[1][0]);

Ideone演示

当您使用preg_match_all时,$subjects是包含所有可能匹配的数组的数组,但第一个匹配(即$subjects[0][0])始终是匹配的整个字符串,而不考虑任何捕获组

尝试只输出捕获组$subjects[1][0],即:

$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
$theSubject = $subjects[1][0];
echo $theSubject;
//This is my subject!

演示

http://ideone.com/ynyidy

除了rock321987的注释之外,另一个解决方案是这样看待look-around断言。

Regex:(?<=Subject:)(.*?)(?=Date:)

Php代码:

<?php
    $theEmail = "Subject:This is my subject!Date:";
    preg_match_all('/(?<=Subject:)(.*?)(?=Date:)/', $theEmail, $subjects);
    print_r($subjects[0]);
?>

Regex101演示

Ideone演示