【问题标题】:PHP Find and replace multiple similar entriesPHP 查找并替换多个相似条目
【发布时间】:2015-01-22 07:17:11
【问题描述】:

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

DeviceIP 10.0.0.1
DeviceIP 10.2.36.4

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

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

显然 IP 地址会改变,所以我无法搜索这些。我知道怎么做一场比赛,但不是多场比赛。

谢谢

【问题讨论】:

标签: php search replace


【解决方案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);

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

【讨论】:

    【解决方案2】:

    这似乎有效:

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

    但这是最好的方法吗?

    【讨论】:

    • 这里每次检查子字符串和计数。最好逐行读取文件并替换您需要的内容
    【解决方案3】:

    只替换第一个匹配项:

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

    【讨论】:

    • 恕我直言,这并不是 OP 所要求的,因为他想更改 IP 而不是字符串 DeviceIP,所以 str_replace 不起作用(这里闻起来是正则表达式,但是您不能仅使用正则表达式更改第 n 次出现)
    • @Chizzle 这是我要更改的 IP 地址,而不是 DeviceIP。有什么办法吗?
    • 假设文件的 IP 地址由换行符分隔,您可以使用 file()。 php.net/manual/en/function.file.php查看有关逐行循环的答案:stackoverflow.com/questions/18991843/…
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2020-04-03
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多