Search code examples
phpstringdnsstrstrparse-url

Compare domains that read from file in php


I have a txt file which contains domains and ips looks like this

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

How do I replace bbb.com to 3.3.3.3 but do not change aaa.bbb.com?

Here is part of my function, but not working at all.

First part I search for the match domain by reading it line by line from file
after I got the matched record ,delete it.
Second part I write a new line into it.

    $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);

after I execute my code, both aaa.bbb.com and bbb.com were deleted, how can I solve this issue?

I've try "parse_url" but "parse_url" only parse url with "http://" prefix instead of a domain.


Solution

  • Well, sorry for the misunderstanding, this should work:

    <?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);
    
    ?>