2013-04-06 116 views
0
$regex = '([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})'; 
$string = 'I am emailing to [email protected] and [email protected] but [email protected]'; 

$newString = preg_replace($regex,'',$string); 

我想用空字符串替換所有的電子郵件地址,只留下前兩個。所以$ newString應該是 I am emailing to [email protected] and [email protected] but。但徒勞無益。將一個字符串中的所有子字符串替換爲離開第一個字符串的兩個字符串 - PHP

我怎麼辦呢....

+0

你沒問幾乎同樣的事情就在最近? – mario 2013-04-06 22:51:15

+0

您的正則表達式是否正確識別所有電子郵件地址? – Sepster 2013-04-06 22:52:56

+0

使用preg_replace_callback並記錄進行了多少次替換。 – 2013-04-06 23:19:45

回答

1

由於通用的答案:

  • 使用preg_splitPREG_SPLIT_DELIM_CAPTURE

  • 在結果數組上,刪除每個具有不均勻索引的數組項,從[4]開始。

  • 然後使用implode()連接其餘部分。

-1

你可以嘗試使用爆炸

$str = I am emailing to [email protected] and [email protected] but [email protected]; 
$str_array = explode(, $str); 
$counter = 0; 
$str_out = ; 
foreach($str_array as $cast){ 
    $findme = @; 
    $pos = strpos($cast, $findme); 
    if ($pos === false) { 
     $str_out = $str_out . $cast . ; 
    }else{ 
     $counter++; 
     if($counter<=2){ 
      $str_out = $str_out . $cast . ; 
     } 
    } 
} 
echo $str_out; 
+0

太複雜了,再加上這個刪除包含@不僅僅是電子郵件地址的任何「單詞」。 – zanbaldwin 2013-04-06 23:22:00

相關問題