1

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.

tommyhsu
  • 27
  • 6
  • If you are writing data like that `$stringData = "bbb.com\n 3.3.3.3\n";` it will have 2 lines for each record: one with the domain and one with the IP address. Is that correct? – Stelian Matei Jun 22 '12 at 08:58
  • sorry that was a mistake it should be like "bbb.com\t 3.3.3.3\n" a tab instead of a newline – tommyhsu Jun 27 '12 at 00:57

2 Answers2

1

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

?>
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • don't forget to add a line on the beginning of the file, (because if bbb.com where on the first line it won't be replaced because there is no \r\n before it !) – HamZa Jun 22 '12 at 10:01
  • I've try this code but it replace bbb.com to 3.3.3.3 it's not the purpose I need. I need to change the "bbb.com 2.2.2.2" to "bbb.com 3.3.3.3",anyway thanks for help. – tommyhsu Jun 27 '12 at 01:36
0

The easiest solution I can think of is to use substr($line,0,7) == 'bbb.com' instead of your strstr comparison.

Konrad Neuwirth
  • 898
  • 5
  • 8
  • but the result is nothing different from strstr, thanks helping – tommyhsu Jun 27 '12 at 02:03
  • There must be another mistake. What the substr does is test for bbb.com at the beginning of the string – so aaa.bbb.com can't match! Ah, and of you need to adapt the == to your actual need; if I read your code correctly, it should be != . – Konrad Neuwirth Jun 27 '12 at 07:43