The Sahil
The Sahil

Reputation: 35

Editing Multiple .php files using PHP

I want to edit 100 php files in different folders using php. I have searched on google but doesn't get any help. I want to replace some text with other text on every file. Tell me a suitable way to do it using php.

For eg. I have two texts t1 ,t2 and i want to replace it with v1,v2 in every file how to do it?.

Upvotes: 0

Views: 632

Answers (2)

Jeff
Jeff

Reputation: 799

  1. PHP is really not the best tool for the job... but it can do it. sed is probably better-suited but definitely has a bit of a learning curve.
  2. You're going to want to use the following functions:
    • opendir
    • str_replace
    • You'll be iterating over each file using a for loop and performing the str_replace() on each file. I recommend not just doing this blindly as it could be very destructive if you make a mistake.

If you've tried this and have a specific problem, come back and post that along with what you've tried!

Upvotes: 1

Samuil Banti
Samuil Banti

Reputation: 1795

$files = array(
    'directory/file1.php',
    'directory/file2.php'
)

$t1 = 'your text 1';
$t2 = 'your text 2';

$t1 = 'your version 1';
$t2 = 'your version 2';

foreach($files as $f) {
   $old_content = file_get_contents($f);
   $new_content = str_replace($t1, $v1, $old_content);
   $new_content = str_replace($t2, $v2, $new_content);
   file_put_contents($f, $new_content);
}

Upvotes: 0

Related Questions