2

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?

4
  • 1
    Try writing something yourself and then if it doesn't work, show us specifically what you did so we can help you along. You start it, we help. We don't write it for you. Show us the actual code that you've tried and then we can help you from there. Chances are you'll get pretty close to the answer if you just try it yourself first. Commented Sep 24, 2013 at 21:21
  • 2
    Why put on hold? It's a decent question, just written badly. Recommend the OP to edit his question. Commented Sep 25, 2013 at 6:37
  • NOTE: The difficulty in this case is not the string ops, but the issue of editing a file apparently in-place. There are several ways to approximate it, none of them are difficult, but none are quite trivial for a beginner either. But the fact that there's practically no way to actually edit a text file "in-place" (despite fseek and fwrite, you'll just end up creating a new one and getting rid of the old, in some way or another) is something that doesn't immediately sink in usually. (It took me some discomfort, too.) Commented Jul 29, 2015 at 10:27
  • For the exec fans sed -i "s/2=.*/2=word/" file.txt Commented Mar 6, 2018 at 14:56

3 Answers 3

11

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
Sign up to request clarification or add additional context in comments.

3 Comments

@loko: I don't think the question is so bad. I assume the OP is a beginner, so I've added the explanation as well, instead of just the code dump.
I'm not saying the question is bad. Even you are assuming the OP is a beginner, dunno if he will understand any of this. Well it's his choice to use it or not.
1

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.

Comments

0

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

4 Comments

Too bad, I really would have loved learning from it.
BTW, the OP didn't exclude the CLI SAPI, so here's a one-line approximation (using regexp for some more usefulness): php -R 'echo preg_replace("/(2_).+/", "$1word", "$argn\n");' <old.txt >new.txt
@Sz. As this post was posted 2 years ago(when I started on SO). I now see how this answer doesnt give enough information to be a good answer, however I still stand by my decision to not actually post the 3 line script I made since the links (and my explanation) should make the exact same script.
@Loco, fair enough. I just followed-up for Googlers, who randomly drop by for some quick juice, just like I ended up here. (BTW, from real PHP code, you can't just do the same as from a cmd.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.