[英]find and replace a specific string of a a particular line in txt file with php
我想知道如何用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。 如果找到匹配项,则将其替换为column:0 OR column: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
我可以得到更正的代码吗?
这就是我要替换的东西。 不用担心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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.