使用php查找并替换txt文件中特定行的特定字符串

时间:2014-03-18 05:22:52

标签: php html text web replace

我想知道如何用php替换特定行的特定单词/字符串到文本文件中。

文本文件的内容如下:

 1|1|1
 nikki|nikki@yahoo.com|nikki
 nikki|nikki@gmail.com|nikki
 nikki|nikki@hotmail.com|nikki

字段详情:

 COLUMN:0 = $name,
 COLUMN:1 = $email,
 COLUMN:2 = $nickname,

更换细节:

 COLUMN:0 = $newName,
 COLUMN:1 = $newEmail,
 COLUMN:2 = $newnickName,     

根据以上内容,您可以猜测查找/搜索基于列:1。如果找到匹配的Ans,则替换列:0 OR列:2 [基于选择]。

我试过[找到专栏:1]:

 $fileData = file("file.txt");
 foreach($fileData as $Key => $Val) { 
  $Data[$Key] = explode("|", $Val);
  if ( trim($Data[$Key][1]) == $email ){
unset($fileData[$Key]);
    //REPLACE TAKE PLACE HERE
    break;
  }
 }

[替换]:

 /* REPLACE NAME */
 $file = "file.txt";
 $oname = "|$name|";$nname = "|$newName|";
 file_put_contents($file, str_replace($oname, $nname, file_get_contents($file)));
 /* REPLACE NICKNAME */
 $file = "file.txt";
 $onickname = "|$nickname|";$nnickname = "|$newnickname|";
 file_put_contents($file, str_replace($onickname, $nnickname, file_get_contents($file)));

但它正在取代所有匹配的“$ name”。

我也尝试过以下方式:

 $fileData[$Key] = str_replace($name, $newName, $fileData[$Key]);
 file_put_contents($file,$fileData);

/* $name & $newName -:> $nickname & $newnickname

但它不起作用。

如果我想用“nikkigmail”替换“nikki@gmail.com”的列:0 [“nikki”],那么数据应为:

 1|1|1
 nikki|nikki@yahoo.com|nikki
 nikkigmail|nikki@gmail.com|nikki
 nikki|nikki@hotmail.com|nikki

并且,如果想用“hotmail”替换“nikki@hotmail.com”的2列[“nikki”],那么:

 1|1|1
 nikki|nikki@yahoo.com|nikki
 nikkigmail|nikki@gmail.com|nikki
 nikki|nikki@hotmail.com|hotmail

我可以获得要更正的代码吗?

1 个答案:

答案 0 :(得分:1)

以下是我将如何替换这样的内容。而不是担心str_replace,为什么不实际修改file返回的数组?

<?php

$email = "nikki@gmail.com"; // Search email
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data

foreach($data as $key => $line) {
    $bits = explode("|", $line);
    if($bits[1] === $email) {
        // Update this in place,
        $bits[0] = "nikkigmail";
        $data[$key] = implode("|", $bits);
    }
}

$write = implode("\n", $data); // the data to write however you please.

请注意,这也可以扩展以满足您的行/列需求。例如,你可以使用这样的东西。

/**
 * The reason these are named differently is because they don't always
 * search/replace. For example, you can find nikki@gmail.com in one row,
 * but just be setting a different column in that row to a value..
 */

$match = array('col' => 1, 'str' => 'nikki@gmail.com'); // Search data at row
$update = array('col' => 0, 'str' => 'nikkigmail'); // Replace data at row

$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data

foreach($data as $key => $line) {
    $bits = explode("|", $line);
    if($bits[$match['col']] === $match['str']) {
        // Update this in place,
        $bits[$update['col']] = $update['str'];
        $data[$key] = implode("|", $bits);
    }
}

$write = implode("\n", $data); // the data to write however you please.