Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line in text file using PHP [closed]

Tags:

regex

replace

php

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?

like image 808
Michael Samuel Avatar asked Mar 23 '26 12:03

Michael Samuel


2 Answers

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
like image 192
Amal Murali Avatar answered Mar 26 '26 01:03

Amal Murali


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.

like image 36
Rociio Lourdes Rodriiguez Avatar answered Mar 26 '26 01:03

Rociio Lourdes Rodriiguez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!