Last active
March 2, 2023 11:59
-
-
Save matteocaberlotto/424ab4731933f0e7ff7ea0a5cb762108 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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