如何 preg_match 在字符串中第一次出现

How to preg_match first occurrence in a string

我正在尝试从电子邮件正文中提取 From:address。这是我目前所拥有的:

$string = "From: user1@somewhere.com This is just a test.. the original message was sent From: user2@abc.com";

$regExp = "/(From:)(.*)/";
$outputArray = array();
if ( preg_match($regExp, $string, $outputArray) ) {
print "$outputArray[2]";
}

我想获取第一次出现的电子邮件地址 From: .. 有什么建议吗?

您的正则表达式太贪心了:.*匹配除换行符外的任何 0 个或更多字符,尽可能多。此外,在文字值周围使用捕获组是没有意义的,它会产生不必要的开销。

使用以下正则表达式:

^From:\s*(\S+)

^ 确保我们从字符串的开头开始搜索,From: 按字面匹配字符序列, \s* 匹配可选空格, (\S+) 捕获1 个或多个非空白符号。

参见sample code

<?php
$string = "From: user1@somewhere.com This is just a test.. the original message was sent From: user2@abc.com";

$regExp = "/^From:\s*(\S+)/";
$outputArray = array();
if ( preg_match($regExp, $string, $outputArray) ) {
print_r($outputArray[1]);
}

您要查找的值在 $outputArray[1] 内。