如何在字符串中首次出现preg_match

sam*_*s39 5 php regex preg-match

我试图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]";
}
Run Code Online (Sandbox Code Playgroud)

我想获得第一次出现From: ..任何建议的电子邮件地址?

Wik*_*żew 5

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

使用以下正则表达式:

^From:\s*(\S+)
Run Code Online (Sandbox Code Playgroud)

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

请参阅示例代码:

<?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]);
}
Run Code Online (Sandbox Code Playgroud)

你正在寻找的价值在里面$outputArray[1].