比较从 php 中读取文件的域


Compare domains that read from file in php

我有一个包含域和 ips 的 txt 文件,如下所示

aaa.bbb.com 8.8.8.8
bbb.com 2.2.2.2
...
...
..

如何将 bbb.com 替换为 3.3.3.3 但不更改 aaa.bbb.com?

这是我职能的一部分,但根本不起作用。

第一部分我通过从文件中
逐行读取匹配域来搜索匹配域在我得到匹配的记录后,删除它。
第二部分我在里面写了一行新行。

    $filename = "record.txt";
    $lines = file($filename);
    foreach($lines as $line) 
    if(!strstr($line, "bbb.com") //I think here is the problem core
    $out .= $line;
    $f = fopen($filename, "w");
    fwrite($f, $out);
    fclose($f);

    $myFile = "record.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $stringData = "bbb.com'n 3.3.3.3'n";
    fwrite($fh, $stringData);
    fclose($fh);

执行代码后,aaa.bbb.com 和 bbb.com 都被删除了,如何解决此问题?

我尝试过"parse_url",但"parse_url"只解析带有"http://"前缀而不是域的 url。

好吧,很抱歉造成误解,这应该有效:

<?php
$file = "record.txt";
$search = "bbb.com";
$replace = "3.3.3.3";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
$dump = "";
foreach($lines as $line){
    $pos = strpos($line, $search);
    if($pos === false){
    echo "<b>$line</b>";
        $dump .= $line.PHP_EOL;
    }else{
        if($pos !== 0){
            $dump .= $line.PHP_EOL;
        }else{
            $dump .= $search." ".$replace.PHP_EOL;
        }
    }
}
$dump = substr($dump,0,-1);
file_put_contents($file, $dump);
?>

我能想到的最简单的解决方案是使用 substr($line,0,7) == 'bbb.com' 而不是您的strstr比较。