2010-09-23 80 views
2

我開發了一個wordpress插件,它通過一堆html查找並檢測任何電子郵件地址,並將其替換爲不可收集的html標記(要通過JavaScript重新顯示爲電子郵件地址更好的可用性)。正則表達式:替換電子郵件地址,扭曲

因此,例如,函數接收:

$content = "Hello [email protected] How are you today?"; 

和輸出:

$content = "Hello <span class="email">john(replace this parenthesis by @)example.com</span>. How are you today?"; 

我的功能工作正常,但我現在想,給指定什麼可讀的電子郵件選項應該是這樣的。因此,如果函數接收:

$content = "Hello [email protected](John Doe). How are you today?"; 

新的輸出將是:

$content = "Hello <span class="email" title="John Doe">john(replace this parenthesis by @)example.com</span>. How are you today?"; 

因此,正則表達式應該尋找附括號,如果找到了,拿裏面有什麼,並添加HTML title屬性,刪除括號,然後解析電子郵件。

因爲功能的可選性質(意思是:那些括號並​​不總是在那裏),所以我對於如何使它發生幾乎一無所知。

任何指針將是有益的,這是我當前的代碼:

function pep_replace_excerpt($content) { 
    $addr_pattern = '/([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})/i'; 
     preg_match_all($addr_pattern, $content, $addresses); 
     $the_addrs = $addresses[0]; 
     for ($a = 0; $a < count($the_addrs); $a++) { 
      $repaddr[$a] = preg_replace($addr_pattern, '<span class="email" title="$4">$1(replace this parenthesis by @)$2.$3</span>', $the_addrs[$a]); 
     } 
     $cc = str_replace($the_addrs, $repaddr, $content); 
     return $cc; 
} 

回答

2

容易的選擇可能與strpos對於剛過電子郵件括號的存在被檢查,然後使用正則表達式來找到((.+?))第一次出現後,電子郵件。

另一種選擇是將((.+?))?添加到您的正則表達式中,最後一個問號將使該組成爲可選。

然後傻瓜代碼如下:

function pep_replace_excerpt($content) { 
    $addr_pattern = '/([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})(\((.+?)\))?/i'; 
     preg_match_all($addr_pattern, $content, $addresses); 
     $the_addrs = $addresses[0]; 
     for ($a = 0; $a < count($the_addrs); $a++) { 
      if(count($the_addrs[$i]) == 4) 
       $repaddr[$a] = preg_replace($addr_pattern, '$1(replace this parenthesis by @)$2.$3', $the_addrs[$a]); 
      else 
       $repaddr[$a] = preg_replace($addr_pattern, '$1(replace this parenthesis by @)$2.$3', $the_addrs[$a]); 
     } 
     $cc = str_replace($the_addrs, $repaddr, $content); 
     return $cc; 
}
+0

很不錯的!有一件事困擾我:4美元將父母一起歸還。有沒有辦法在正則表達式中刪除它們?否則,我想我可以通過PHP函數修復。 – pixeline 2010-09-23 08:38:11

+0

謝謝:)我編輯了正則表達式模式,以便該組只是括號內的文本。 – 2010-09-23 09:18:42

+0

mmh,不能很好地工作:它似乎與右括號一起失敗。我會繼續努力...... HEre是一個複製/可讀代碼:http://phpbin.net/x/196328853 – pixeline 2010-09-23 09:29:26

相關問題