0

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?.

1
  • I'd probably use sed on the command line, but you run the risk of making unexpected changes if you are not careful. Alternatively, let your tools do the heavy lifting: have a look at your favourite IDE/file editor - it might have multi-file search and replace? For instance, Sublime Text has Find in Files.. feature that allows multi-file search and replace, optionally with regex pattern matching. As advised below, I would take an incremental approach - do not blindly run a destructive process on your files! Commented Mar 31, 2014 at 9:35

2 Answers 2

1
  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!

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

Comments

0
$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);
}

2 Comments

First i tried this put it don't able to do my work. Now looking at ur code i get what i want. Thanks i will modiy it. My code: <?php foreach(glob("path/to/files/*.txt") as $filename) { $file = file_get_contents($filename); file_put_contents($filename,preg_replace("/regexhere/","replacement",$file)); } ?> the problem with above code is that i can perform only one replacement but i have to make many replacement. Now i can do it by checking your code. Thank you for help.
I think that str_replace (php.net/manual/en/function.str-replace.php) is the best way to do it.

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.