0

I am using fopen to reach my PHP file :

$readFd = @fopen($file, 'r+');

I would like to search this file for the function call parent::process(); And if this exists I would then insert a new function call after this.

I have tried using preg_replace but it does not seem to match parent::process(); For example the result I need is this.

public function process() {
  parent::process();
  $this->newFunction();
}

Then to write the to the file I am using :

fwrite($readFd, $content);

I guess I must be missing something important with regex. Hopefully someone can point me in the right direction.

2 Answers 2

2

I would use the php function fgets to read every in the file one by one until you reach the line you need. And then your pointer will be after that line where you can write your own line.

EDIT

I was wrong, when you write something to a file at a specific point, everything after that point is lost. So I did a little testing and came up with this:

$handle = fopen($file,"r+");

$lines = array();
while(($line = fgets($handle)) !== false) {
    $lines[] = $line;
    if(strpos($line, 'parent::process()')) {
        $lines[] = '$this->newFunction();';
    }
 }
 fseek($handle, 0); // reset pointer
 foreach($lines as $line) {
    fwrite($handle, $line);
 }
 fclose($handle);

I hope this solves your problem.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks this is a step further :) I have now matched my function however I am still not sure how to write to the next line after my match. while(($line = fgets($readFd)) !== false) { if(strpos($line, "parent::process()")) // I want to insert after finding parent::process ??? } If I use fwrite it still appends to the file.
ok I am finally back to my project and confirm your solution is simpler and it works well :)
0

I came up with the solution however your code seems much shorter so I will try your solution tomorrow.

if(! $readFd = @fopen($file, "r+"))
  return FALSE;

$buffer = fread($readFd, 120000);
fclose($readFd);
$onDuplicate = FALSE;
$lines = explode("\n", $buffer);
foreach($lines AS $key => $line) {
  if(strpos($line, "newFunction()")) {
    $onDuplicate = TRUE;
  }
  if(strpos($line, "parent::process()")) {
    $lines[$key] = "\t\tparent::process();\n\t\t//\$this->newFunction();\n";
  }
}

if(! $onDuplicate) {
  $readFd = fopen($file, "w");
  $buffer = implode("\n", $lines)."\n";
  fwrite($readFd, $buffer);
  fclose($readFd);
} else {
  var_dump('changes are already applied');
}

Thanks for all your help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.