使用PHP替换文件中的损坏的电子邮件地址

时间:2014-12-05 14:23:05

标签: php regex preg-replace

我有一个包含电子邮件列表的文件file.txt

email@domain.com
email@domain2.com
email@domain3.com
email@domain4.com
email@domain5.com
@domain.com
email@domain6.com
email@domain7.com

我需要从列表中删除@ domain.com。我正在使用此代码:

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

但这也会从@domain.com中移除email@domain.com,使其成为不正确的列表。

我该怎么做?

4 个答案:

答案 0 :(得分:2)

您也可以使用正则表达式来匹配整行。从头到尾,这将是:

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

如果你想删除该行而不是将其清空,那么正则表达式将是"/^@domain\.com[\n]$/m"

答案 1 :(得分: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 :(得分: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));

答案 3 :(得分:0)

如果@是句子的开头,你可以尝试使用像(^@domain\.com)那样的正则表达式只能替换@ domain.com