[英]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.