我有一个文件文件.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')));
但这也会从email@domain.com
中删除@domain.com
,使其成为不正确的列表。
我该怎么做?
您也可以使用正则表达式来匹配整行。从我的头顶上看,这将是:
<?php
file_put_contents('file.txt',
preg_replace("/^@domain'.com$/m","",file_get_contents('file.txt')));
如果要删除该行而不是将其留空,则正则表达式将"/^@domain'.com['n]$/m"
你可以尝试使用正则表达式,如果@是句子的开头,(^@domain'.com)
应该只替换@domain.com
你应该
在每一行上使用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));
您可以确定 @ 符号的位置,并仅在它是行中的第一个字符时才替换。
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'));