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?
You don't need a regex for this. Try the following:
file() and loop through the lines2_$word and concatenate it to the $result string$result stringfile_get_contents() and write the result to the fileCode:
$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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With