2014-12-05 22 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

相关问题