2011-12-22 62 views
14

我想让脚本搜索$ open_email_msg,其中不同的电子邮件将具有不同的信息,但格式如下。在strpos中使用正则表达式()

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

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

会甚至工作。

这仅仅是一个整个代码的片段,其余插入信息到一个MySQL表,然后张贴到网站上的新闻文章。

有人可以帮我找到一个解决方案对此请?

严格的电子邮件消息格式:

新闻更新
标题:文章标题
标签:标签1标签2
分类:文章分类,第二条分类
段: 文章片段。
消息:文章消息。图片。更多文字, 更多文字。 Lorem impsum dolor坐在amet上。

<?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 
?> 

回答

16

尝试使用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变量,一个空字符串,如果没有标题被发现。

4

您可以改为使用的preg_match strpos对正则表达式

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

PREG_OFFSET_CAPTURE gives you the position of match.