PHP查找并替换多个类似条目

时间:2014-11-24 14:32:05

标签: php search replace

我有一个包含大约60行的文本文件。其中有2行:

DeviceIP 10.0.0.1
DeviceIP 10.2.36.4

我有一个PHP表单,其中包含$device1& $device2

如何在文件中查找和替换,用$ device1替换第一个DeviceIP,用$ device2替换第二个?

显然,IP地址会发生变化,因此我无法搜索这些地址。我知道怎么做一场比赛,但不是多场比赛。

由于

3 个答案:

答案 0 :(得分:1)

你可以这样试试。

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

它将用数组值替换字符串出现。 这是逐行阅读并取代匹配,我认为这很好。

答案 1 :(得分:0)

仅替换第一次出现:

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

答案 2 :(得分:0)

这似乎有效:

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

但这是最好的方法吗?