views:

152

answers:

3

I'm trying to find some certain blocks in my data file and replace something inside of them. After that put the whole thing (with replaced data) into a new file. My code at the moment looks like this:

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  preg_replace('/regexp2/su', 'replacement', $match);
}

file_put_contents('new_file.ext', return_whole_thing?);

Now the problem is I don't know how to return_whole_thing. Basically, file.ext and new_file.ext are almost the same except of the replaced data. Any suggestion what should be on place of return_whole_thing?

Thank you!

+1  A: 

You don't even need the preg_replace; because you've already got the matches you can just use a normal str_replace like so:

$content = file_get_contents('file.ext', true);

//find certain pattern blocks first
preg_match_all('/regexp/su', $content, $matches);

foreach ($matches[0] as $match) {
  //replace data inside of those blocks
  $content = str_replace( $match, 'replacement', $content)
}

file_put_contents('new_file.ext', $content);
Swizec Teller
A: 

I'm not sure I understand your problem. Could you perhaps post an example of:

  • file.ext, the original file
  • the regex you want to use and what you want to replace matches with
  • new_file.ext, your desired output

If you just want to read file.ext, replace a regex match, and store the result in new_file.ext, all your need is:

$content = file_get_contents('file.ext');
$content = preg_replace('/match/', 'replacement', $content);
file_put_contents('new_file.ext', $content);
Steven Xu
A: 

It's probably best to strengthen your regular expression to find a subpattern within the original pattern. That way you can just call preg_replace() and be done with it.

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);

This can be done with "( )" within the regular expression. A quick google search for "regular expression subpatterns" resulted in this.

munch