2014-12-05 21 views
1

我有一個包含電子郵件更換損壞的電子郵件地址,使用PHP

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
@domain.com 
[email protected] 
[email protected] 

我需要從列表中刪除@ domain.com列表的文件file.txt的。我使用此代碼:

file_put_contents('file.txt', 
        str_replace("@domain.com","",file_get_contents('file.txt'))); 

但是,這也將刪除[email protected]@domain.com,使其成爲一個不正確的列表。

我該怎麼做?

回答

0

您可以確定@符號的位置,並僅在該符號是行中的第一個字符時才進行替換。

function replacethis($file){ 
    $str = ''; 
    $a = file_get_contents($file); 
    foreach ($a as $b) { 
     if (strpos($b,'@') == 0) { 
      $str .= str_replace('@domain.com','',$b)."<br>"; } 
     else { 
      $str .= $b."<br>"; 
     }} 
    return $str; 

} 
file_put_contents('file.txt', replacethis('file.txt')); 
2

你也可以使用正則表達式匹配整行。從我的頭頂,這將是:

<?php 
file_put_contents('file.txt', 
        preg_replace("/^@domain\.com$/m","",file_get_contents('file.txt'))); 

如果你想刪除的,而不是使其成爲空正則表達式將"/^@domain\.com[\n]$/m"

+0

感謝您的開頭! ereg_replace也不錯? – gr68 2014-12-05 14:37:53

+0

您可以使用該方法。但似乎這種方法已被廢棄(如http://php.net/manual/en/function.ereg-replace.php中所述)。所以最好使用preg_replace(或preg_replace_all) – 2014-12-05 14:39:25

+1

你必須逃避點,因爲它意味着任何字符。 – Toto 2014-12-05 15:12:56

0

您應該使用的preg_replace行:每行http://php.net/manual/en/function.preg-replace.php

這將刪除每個電子郵件地址,該地址在開頭沒有用戶名。

$file = new SplFileObject("file.txt"); 
$emailAddresses = array(); 
while (!$file->eof()) { 
    $email = trim(preg_replace("/^@(.*)$/", "", $file->fgets())); // If you only want to remove specific addresses from a specific domain, change (.*) to domain\.com 

    if (strlen($email)) { 
     $emailAddresses [] = $email; 
    } 
} 
file_put_contents("file.txt", join(PHP_EOL, $emailAddresses)); 
0

你可以嘗試使用正則表達式像(^@domain\.com)應該只更換@ domain.com如果@是句子

+0

正則表達式不適用於str_replace – gr68 2014-12-05 14:37:03

+0

你可以使用preg_replace,但我沒有寫代碼,因爲我不是一個PHP開發人員,我只是知道一個正則表達式會做這項工作,並希望你能填補它的位 – 2014-12-05 14:40:30

相關問題