2014-02-12 46 views
0

我有一個ICS文件,當在谷歌日曆,雅虎日曆等創建會議時,將上傳到我的服務器....我已解析日期,組織者等。從ics文件。但我無法獲得與會者名單。以下是代碼將在ICS文件中。在PHP中解析字符串

BEGIN:VEVENT 

ATTENDEE;RSVP=TRUE:mailto:xxxxxxx 

    [email protected] 
ATTENDEE;RSVP=TRUE:mailto:[email protected] 

ATTENDEE;RSVP=TRUE:mailto:[email protected] 

ATTENDEE;RSVP=TRUE:mailto:[email protected] 

CLASS:PUBLIC 

從上面的代碼,我需要電子郵件ID與mailto參數相關聯。請幫我實現這一點。

<?php 
$cal = file_get_contents("ics_files/outlook.ics"); 
$cal = str_replace("\n", "", $cal); 
preg_match_all('/mailto:(.*?)ATTENDEE/', $cal, $attendees); 
?> 
+0

@Nenotlep我曾嘗試正則表達式。但它並不能提取我想要的東西。 –

+1

@VinayakInfotech:然後請發佈您迄今爲止所嘗試的結果以及您目前獲得的預期結果和結果。 –

+0

@AmalMurali我已經添加了問題中的代碼。 –

回答

1

如果刪除預格式化線去除從ICS數據換行符(\n),一個簡單的正則表達式可用於:

/mailto:(.*?)(?:ATTENDEE;|CLASS:)/s 

/s通知正則表達式引擎匹配換行符與.。如果你想砸/s,你也可以使用:

/mailto:((?:\r\n|\n|.)*?)(?:ATTENDEE;|CLASS:)/ 

使用PHP的preg_match_all()

preg_match_all('/mailto:(.*?)(?:ATTENDEE;|CLASS:)/s', $cal, $attendees); 

輸出:

print_r($attendees[1]); 

Array (
    [0] => xxxxxxx 

    [email protected] 
    [1] => [email protected] 
    [2] => [email protected] 
    [3] => [email protected] 
) 

然後,您可以遍歷$attendees[1]陣列應用您希望的任何電子郵件地址邏輯/格式。

例子:

foreach ($attendees[1] as $attendee) { 
    // remove any extra spaces/newlines from the address 
    $attendee = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", ' ', $attendee))); 

    // split the address into any available name/email-address combination 
    $address = explode(' ', $attendee); 

    echo $address[0]; 
    if (!empty($address[1])) { 
     // there is a name/email-address combination available 
     echo ' <' . $address[1] . '>'; 
    } 
    echo "\n"; 
} 

輸出:

xxxxxxx <[email protected]> 
[email protected] 
[email protected] 
[email protected] 
-1

嘗試在單行這個

preg_match_all('/mailto:(.+)/', $str, $matches); 
echo "<pre>"; 
print_r($matches[1]); 
+0

此代碼將從mailto:開始返回所有內容。但是我需要在數組中使用確切的電子郵件ID。 –

+0

否,僅返回所有電子郵件ID。 Mailto不在那裏。再次檢查 –

0

你從文件中刪除所有的換行符,從而使一切。由於.*?與任何不是換行符(非貪婪匹配)的字符匹配,您將收到包含空格的電子郵件 - 例如,xxxxxxx [email protected]將與匹配。

你可以更具體一些,並限制正則表達式匹配(並捕獲)mailto:其次是任何不是空格的東西,後面跟着任何空格字符(可以是選項卡,換行符或不同的空格字符):

preg_match_all('/mailto:(\S+)\s/', $cal, $attendees); 
print_r($attendees[1]); 

這將返回下面的數組:

Array 
(
    [0] => xxxxxxx  /* <--- not valid */ 
    [1] => [email protected] 
    [2] => [email protected] 
    [3] => [email protected] 
) 

然而,這些都是不仍然是有效的電子郵件地址。如果您還想驗證這些電子郵件地址並過濾掉那些無效的郵件地址,則可以使用array_filter()filter_var驗證作爲回調 - 這比使用正則表達式來實現任務更容易。

if ($match) { 
    $valid_emails = array_filter($attendees[1], function ($email) { 
     return filter_var($email, FILTER_VALIDATE_EMAIL); 
    }); 
} 

print_r($valid_emails); 

輸出:

Array 
(
    [1] => [email protected] 
    [2] => [email protected] 
    [3] => [email protected] 
) 
0

試試這個表達式,

/ATTENDEE.*mailto:(\S+)/g 

它會所有與會者的郵件只匹配

+0

只需注意:PHP沒有'g'修飾符 - 您可以使用'preg_match_all'來實現此功能。 –

+0

是的,錯過了 –