我试图解析一封电子邮件并找到最后一次出现的模式XXXX-XX-XX,其中X是一个整数。然后我想将其插入到数据库中,但每次都要输入EA。其他部分(正文和发布)已成功解析。
// PULL IN EMAIL
$Parser = new PhpMimeMailParser\Parser();
$Parser->setStream(fopen("php://stdin", "r"));
// SET VAIABLES OF 'FROM' AND 'BODY'
$from_raw = $Parser->getHeader('from');
$entry_raw = $Parser->getMessageBody('text');
// GRAB NAME AND EMAIL FROM 'FROM'
$from = preg_split('/\s*<([^>]*)>/', $from_raw, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$regex = '/.*\b\K\d{4}-\d{2}-\d{2}/s';
preg_match_all($regex, $entry_raw, $date, PREG_SET_ORDER, 0);
$date = $date[0][0];
// TRIM 'BODY' DOWN TO FIRST PARAGRAPH
$entry = explode("\n", $entry_raw);
// CONNECT TO DATABASE
$hostname = "xxx";
$database = "xxx";
$username = "xxx";
$password = "xxx";
$con = mysqli_connect($hostname, $username, $password, $database) or die (mysql_error());
if ($con->connect_error) {
die("ERROR: Unable to connect: " . $con->connect_error);
}
$stmt = $con->prepare("SELECT id FROM users WHERE email=?");
$stmt->bind_param("s", $from[1]);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$stmt->close();
if ($id) {
$stmt = $con->prepare("INSERT INTO entries (entry, user_id, date) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $entry[0], $id, $date);
$stmt->execute();
$stmt->close();
}
我已在单独的文件中尝试过此代码,但效果很好:
$entry_raw = "this is some text 1111-11-11 2222-22-22 this is some more text";
$regex = '/.*\b\K\d{4}-\d{2}-\d{2}/s';
preg_match_all($regex, $entry_raw, $date, PREG_SET_ORDER, 0);
$date = $date[0][0];
echo $date;