19

我想让脚本搜索 $open_email_msg 不同的电子邮件将有不同的信息,但格式如下。

我并没有真正使用正则表达式,但我想做的是每当我有它搜索它会搜索“标题:[标题数据]”,“类别:[类别数据]的字符串。我在问因为我不认为像

strpos($open_email_msg, "Title: (*^)"); 

甚至会工作。

这只是整个代码的一个片段,其余部分将信息插入到 MySQL 表中,然后发布到网站上的新闻文章中。

有人可以帮我找到解决方案吗?

严格的电子邮件格式:

新闻更新
标题:文章标题
标签:tag1 tag2
类别:文章类别,第 2 篇文章类别
片段:文章片段。
消息:文章消息。图片。更多文字,更多文字。Lorem impsum dolor 坐在一起。

<?php
    //These functions searches the open e-mail for the the prefix defining strings.
        //Need a function to search after the space after the strings because the subject, categories, snippet, tags and message are constant-changing.
    $subject = strpos($open_email_msg, "Title:");       //Searches the open e-mail for the string "Title" 
        $subject = str_replace("Title: ", "" ,$subject);
    $categories = strpos($open_email_msg, "Categories:");       //Searches the open e-mail for the string "Categories"
    $snippet = strpos($open_email_msg,"Snippet");           //Searches the open e-mail for the string "Snippet"
    $content = strpos($open_email_msg, "Message");  //Searches the open-email for the string "Message"
    $tags = str_replace(' ',',',$subject); //DDIE
    $uri =  str_replace(' ','-',$subject); //DDIE
    $when = strtotime("now");   //date article was posted
?>
4

2 回答 2

29

尝试将PREG_OFFSET_CAPTURE标志用于preg_match. 像这样的东西:

preg_match('/Title: .*/', $open_email_msg, $matches, PREG_OFFSET_CAPTURE);
echo $matches[0][1];

这应该为您提供字符串的初始位置。

请注意,我使用的正则表达式可能是错误的,并且没有考虑行尾和其他内容,但这是另一个主题。:)

编辑。你想要的更好的解决方案(如果我理解正确的话)是这样的:

$title = preg_match('/Title: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';

然后将标题放入$title变量中,如果没有找到标题,则为空字符串。

于 2011-12-22T21:19:39.760 回答
8

您可以使用 preg_match 而不是 strpos 进行正则表达式

preg_match (regex, $string, $matches, PREG_OFFSET_CAPTURE);

PREG_OFFSET_CAPTURE gives you the position of match.
于 2011-12-22T21:27:21.937 回答