我正试图从电子邮件中抓取主题。
这有效:
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
但是这样的回报:
"Subject:This is my subject!Date:"
我只想这是我的主题!根据我所读到的,这就是我应该得到的。我错过了什么?
答案 0 :(得分:2)
您可以使用subjects[1][0]
来访问值
$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/Subject:(.*?)Date:/', $theEmail, $subjects);
print_r($subjects[1][0]);
<强> Ideone Demo 强>
使用preg_match_all
时,$subjects
是包含所有可能匹配的数组数组,但第一个匹配即$subjects[0][0]
始终是匹配的整个字符串,与任何捕获组无关< / p>
答案 1 :(得分:0)
除了rock321987的评论之外的另一个解决方案是查看look-around
这样的断言。
正则表达式: (?<=Subject:)(.*?)(?=Date:)
Php代码:
<?php
$theEmail = "Subject:This is my subject!Date:";
preg_match_all('/(?<=Subject:)(.*?)(?=Date:)/', $theEmail, $subjects);
print_r($subjects[0]);
?>
<强> Regex101 Demo 强>
<强> Ideone Demo 强>
答案 2 :(得分: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!
<强>样本强>