我有一个文本文件,并且在此文本文件中是域。我想删除所有没有.com .nl和.be扩展名的域。因此,基本上,必须使用.org,.de等域名。所有域扩展名都保存在$ key变量中。是否可以创建一个循环,而不是复制粘贴代码并更改变量?
这是有效的,因为它是一个变量:
<?php
$key0 = ".org";
$fc=file("linklijst.txt");
$f=fopen("linklijst.txt","w");
foreach($fc as $line)
{
if (!strstr($line,$key0))
fputs($f,$line);
}
fclose($f);
?>
但这不是:
<?php
$keys = array(".org",".de",".fr",".pl",".es",".uk",".jp",".ro",".forum",".us",".in",".it",".co",".ie",".ru",".dk",".tk",".pro",".ml",".gg",".cf",".hu",".kz",".ooo",".ca",".kr",".win",".cz",".ga","se");
$fc=file("linklijst.txt");
$f=fopen("linklijst.txt","w");
foreach($fc as $line)
{
if (!strstr($line,$keys))
fputs($f,$line);
}
fclose($f);?>
答案 0 :(得分:0)
假设您的文件:domains.txt如下:
example.com
example.net
example.nl
example.de
example.org
example.be
您只希望保留.com,.be和.nl的内容
$preserve = ['.com', '.nl', '.be'];
$accepted = []; //will contain the lines we want to preserve.
$lines = file("domains.txt");
foreach($lines as $line) {
$suffix = substr($line, strrpos($line, ".")); //get the domain suffix
if (in_array($suffix, $preserve)) {
$accepted[] = $line;
}
}
print_r($accepted);
这可能不是最健壮的代码,但我希望它能说明解决问题的一种不错的方法。