Skip to content

Instantly share code, notes, and snippets.

@matteocaberlotto
Last active March 2, 2023 11:59
Show Gist options
  • Save matteocaberlotto/424ab4731933f0e7ff7ea0a5cb762108 to your computer and use it in GitHub Desktop.
Save matteocaberlotto/424ab4731933f0e7ff7ea0a5cb762108 to your computer and use it in GitHub Desktop.
<?php
if ($argc < 5) {
echo <<<EOF
Use:
php modify.php <filename> <variable> <from> <to> <backup>
EOF;
exit(1);
}
function find_line($lines, $needle) {
foreach ($lines as $index => $line) {
if (stripos($line, $needle) !== false) {
return $index;
}
}
return false;
}
$file = $argv[1];
$variable = $argv[2];
$from = $argv[3];
$to = $argv[4];
$backup = isset($argv[5]) ? true : false;
$content = file_get_contents($file);
$search_env_var = "{$variable}={$from}";
if (stripos($content, $search_env_var) !== false) {
$lines = explode("\n", $content);
$line_num = find_line($lines, "{$variable}=");
$new_lines = [];
if ($backup) {
$new_lines []= "#{$variable}={$from}";
}
$new_lines []= "{$variable}={$to}";
$offset = $line_num;
$result = array_slice($lines, 0, $offset);
foreach ($new_lines as $new_line) {
$result []= $new_line;
}
$offset++;
for ($i = $offset; $i<count($lines); $i++) {
$result []= $lines[$i];
}
echo "Replacing lines of {$file}\n";
file_put_contents($file, implode("\n", $result));
} else {
echo "Not found in {$file}\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment