简体   繁体   English

检查每一行到特定字符的最有效方法是什么

[英]What is the most efficient way to check each line up to a certain character

If I pipe an email into a PHP script, and go through each line using fgets , what is the best way to filter out the values from the From: To: and Subject: lines? 如果我将电子邮件发送到PHP脚本中,并使用fgets遍历每一行,那么从“ From: To:和“ Subject:行中筛选出值的最佳方法是什么?

I was thinking about exploding each line at : and then checking if ($result[0] === 'To') and so on, but then I'm exploding each line, when I should only be doing that for From , To and Subject 我当时正在考虑在:每行,然后检查if ($result[0] === 'To') ,依此类推,但是当我只应该对FromTo进行此操作时,我正在展开每一行。和Subject

From a Google/SO search I found substr() but you need to specify the number of characters to search, which is different for each value I want. 在Google / SO搜索中,我找到了substr()但是您需要指定要搜索的字符数,这对于我想要的每个值都是不同的。

There is a page out to parse mail headers - They are sharing their regular expressions they are using, so maybe you can simple grab the parts you need: 有一个页面可以解析邮件头-它们共享它们正在使用的正则表达式,因此也许您可以简单地获取所需的部分:

http://mailheader.mattiasgeniar.be/headers.php http://mailheader.mattiasgeniar.be/headers.php

The Regular Expressions suggested for your desired fields are: 建议用于所需字段的正则表达式为:

From     |^from:(.*)|mi 
To       |^to:(.*)|mi 
Subject  |^subject:(.*)|mi 

you could do something like: 您可以执行以下操作:

$finds = array('Subject:', 'From:', 'To:');
$founds = array();

$line = fgets(...); // whatever your logic is to get each line

foreach($finds as $key => $find){

    if (substr(trim($line), 0, strlen($find)) == $find){
        $founds[] = array($find, $line);
    }

} 

print_r($founds);  // you can explode (or whatever) the data as needed

this is untested, i just typed it out :) 这是未经测试的,我只是输入了:)

You could use regular expressions do something like this, for each input $line : 您可以对每个输入$line使用正则表达式执行$line

$matches = array();
$params = array();
if (preg_match('/^Subject: (.*)/', $line, $matches) == 1) {
    $params['subject'] = $matches[1];
} elseif (preg_match('/^From: (.*)/', $line, $matches) == 1) {
    $params['from'] = $matches[1];
} elseif (preg_match('/^To: (.*)/', $line, $matches) == 1) {
    $params['to'] = $matches[1];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM