Replace line in text file using PHP [closed]

2019-02-20 06:49发布

问题:

I have a text file with the following data:

1_fjd
2_skd
3_fks

I want to replace a part in my text file using php. For example I want to do this:

Find the line that starts with "2_" and replace it with "2_word", so everything after '2_' is being replaced by:'word'. How can I do this in php?

回答1:

You don't need a regex for this. Try the following:

  • Load the file into an array using file() and loop through the lines
  • Check if the string starts with 2_
  • If it does, replace it with the input $word and concatenate it to the $result string
  • If if doesn't, simply concatenate it to the $result string
  • Use file_get_contents() and write the result to the file

Code:

$lines = file('file.txt');
$word = 'word';
$result = '';

foreach($lines as $line) {
    if(substr($line, 0, 2) == '2_') {
        $result .= '2_'.$word."\n";
    } else {
        $result .= $line;
    }
}

file_put_contents('file.txt', $result);

Now, if the replace took place, then file.txt would contain the something like:

1_fjd
2_word
3_fks


回答2:

File:

1_fjd
2_skd
1_fff

Calling:

replaceInFile("1_", "pppppppppp", "test.txt");

Output:

1_pppppppppp
2_skd
1_pppppppppp

Function:

function replaceInFile($what, $with, $file){
    $buffer = "";
    $fp = file($file);
    foreach($fp as $line){
        $buffer .= preg_replace("|".$what."[A-Za-z_.]*|", $what.$with, $line);
    }
    fclose($fp);
    echo $buffer;
    file_put_contents($file, $buffer);
}

PS: will only work if you have only letters from a to Z after $what. If you want to support more characters you have to change the preg_replace pattern.



回答3:

Okay I've just made this myself with just 3 lines. I am not going to post it cause you wont learn from it. I will tell you what you need. explode (to show that everything after the 1st _ has to be replaced) and str_replace (to replace of couse) Just read the manual and you will be able to understand it. Good luck

EDIT: and of course: fopen