0

I've got a text file which contains about 60 lines. Within in that are 2 lines:

DeviceIP 10.0.0.1
DeviceIP 10.2.36.4

I have a PHP form which has $device1 & $device2

How do I find and replace in the file, replacing the first DeviceIP with $device1 and the second with $device2 ?

Obviously the IP Addresses will change so I can't search on those. I know how to do it for one match, but not multiple.

Thanks

3

3 Answers 3

1

You can try like this.

           $arr=array('10.0.0.10','10.22.32.12');
            $handle = fopen("test.txt", "r");
            $str="";
            if ($handle) {
                $count=0;
                while (($buffer = fgets($handle, 4096)) !== false) {
                    if(preg_match("/DeviceIP/", $buffer)){
                        $str.= "DeviceIP ".$arr[$count];
                        $str.="\n";
                    }
                    $count++;
                }
                if (!feof($handle)) {
                    echo "Error: unexpected fgets() fail\n";
                }
                fclose($handle);
            }
            file_put_contents('test',$str);

It will replace string occurrence with array value. and this is reading line by line and replace match, I think it is good.

Sign up to request clarification or add additional context in comments.

Comments

0

Replace only the first occurrence:

$str = file_get_contents('yourtextfile.txt');

$str = str_replace("DeviceIP", $device1, $str, 1); // Replace only first occurrence

$str = str_replace("DeviceIP", $device2, $str, 1); // Replace second occurrence

file_put_contents('yourtextfile', $str);

3 Comments

IMHO this is not excatly what OP asked for as he want to change the IP not the string DeviceIP, so the str_replace won't work (it smells regex here, but you can't change nth occurrence with regex only)
@Chizzle it's the IP Address I want to change not DeviceIP. Any way to so that ?
Assuming the file's IP addresses are seperated by line breaks, you can use file(). php.net/manual/en/function.file.php Check out this answer about looping through line by line: stackoverflow.com/questions/18991843/…
0

This seems to work:

$test = file('test');
$result = ''; $count ='1';
foreach($test as $v) {
    if (substr($v,0,8) == 'DeviceIP' && $count =='1') {
        $result .= "DeviceIP $device1\n"; $count++;
    } elseif (substr($v,0,8) == 'DeviceIP' && $count =='2') {
        $result .= "DeviceIP $device2\n";
    } else {
        $result .= $v;
    }
}
file_put_contents('test', $result);

But is it the best way to do this ?

1 Comment

Here every time you are checking sub string and count. It is better to read file line by line and replace what you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.