Wallogit.com
2017 © Pedro Peláez
A search/replace class with zero overhead.
magicreplace is a search replace tool for migrating databases., (*2)
When moving databases, usually the url environment also changes. If the URL is hardcoded in the database (like WordPress does), those URLs have to be changed. If you now do a search and replace on your entire database to change the URLs, you will corrupt data that has been serialized. Just try out, (*3)
unserialize(str_replace('www.foo.tld', 'www.barrr.tld', serialize('url=www.foo.tld')));
and you will get an ugly error., (*4)
This does not release you from taking backups. Use this script at your own risk!, (*5)
brew install coreutils
Runs out of the box with WSL/WSL2/Cygwin., (*6)
–, (*7)
wget https://raw.githubusercontent.com/vielhuber/magicreplace/master/src/magicreplace.php
php magicreplace.php input.sql output.sql search-1 replace-1 search-2 replace-2
composer require vielhuber/magicreplace
<?php
require __DIR__ . '/vendor/autoload.php';
use vielhuber\magicreplace\magicreplace;
magicreplace::run('input.sql', 'output.sql', ['search-1' => 'replace-2', 'search-2' => 'replace-2']);
If you want for example to replace http://www.foo.tld with https://www.bar.tld, the safest method to do so is with the following replacements (in the given order):, (*8)
http://www.foo.tld https://www.bar.tld
https://www.foo.tld https://www.bar.tld
http://foo.tld https://www.bar.tld
https://foo.tld https://www.bar.tld
www.foo.tld www.bar.tld
foo.tld bar.tld
Just place these 3 files in a (optionally nested) subfolder of tests/data:, (*9)
input.sql: The desired input fileoutput.sql: The desired output filesettings.sql: Define your replacementsExample settings.sql file:, (*10)
{
"replace": {
"http://www.foo.tld": "https://www.bar.tld",
"https://www.foo.tld": "https://www.bar.tld"
}
}
If a test fails, the expected output is stored in expected.sql., (*11)
You can even auto generate test cases (that compares magicreplace to Search-Replace-DB and only gives you the diff) if you omit input.sql and output.sql and define a mysql database to dump from locally. Example settings.sql file:, (*12)
{
"source": {
"host": "localhost",
"port": "3306",
"database": "xxx",
"username": "xxx",
"password": "xxx",
},
"replace": {
"http://www.foo.tld": "https://www.bar.tld",
"https://www.foo.tld": "https://www.bar.tld"
}
}
input.sql and output.sql then get generated automatically. After you rerun the tests, these generated files are used. If you want to generate them again, just delete them before running the test. You also can provide a whitelist.sql file that includes all lines from input.sql that should be ignored (e.g. where magicreplace acts differently from Search-Replace-DB)., (*13)