2011-12-22 69 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.