SearchReplace is a PHP library aimed at executing search and replace queries on the database and even handles json, serialized data, and base64 replacements.
Without composer
require 'src/SearchReplace.php';
$request = new SearchReplace();
$request->setDatabase($host, $username, $password, $database)
->search($needle, $search_regex)
->replace($needle, $search_regex)
->execute();
Using composer autoload
// require autoloader
require 'vendor/autoload.php';
// use namespace
use SearchReplace/SearchReplace;
// .. somewhere in your file
$request = new SearchReplace();
$request->setDatabase()
->search($needle, $search_regex)
->replace($needle, $search_regex)
->execute();
Create a custom database resource that we can pass around. Specify tables to exclude during search execution.
// create custom database connection
$db_instance = new SearchReplaceMySQLDatabase($host, $username, $password, $database);
$exclude_tables = [
'craft_entries'
'wp_posts',
'wp_postmeta'
];
$request = new SearchReplace();
$request->setDatabase($db_instance)
->search($needle, $search_regex)
->replace($needle, $search_regex)
->includeAllTables(true)
->excludeTables($exclude_tables)
->setTableOffset(50)
->setTableLimit(10)
->execute();
You can pass in a database resource or you can allow the class to create a new database resource by providing the full database credentials.
- Expects either a database resource or if you want the class to create a new connection, provide the host address as a string.
Database resource example:
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$request = new SearchReplace();
$request->setDatabase($mysqli);
Database resource example shortened:
$request = new SearchReplace(new mysqli('localhost', 'user', 'password', 'database'));
Credentials example:
$request = new SearchReplace();
$request->setDatabase('localhost', 'user', 'password', 'database');
- The username needed to connect to the database.
- The password needed to connect to the database.
- The name of the database.
Call this method to define a search on the database. This is also useful in performing dry runs.
- The value to find in the database
- Whether the search needle is a RegEx pattern
Call this method to define replacements on the database.
- The value to replace the search needle with
- Whether the replace value is a RegEx pattern
Adds all tables to the search queue. Defaults to true.
- True - enables adding all tables to the search queue.
- False - disables adding all tables to the search queue.
Allows you to specify what tables are in the search queue.
- An array containing the tables to perform the search on.
- Whether to override any previously set include tables.
- An array containing the tables that should not be searched.
Resets all table inclusions, exclusions, table ranges, and table row ranges
Resets table inclusions and exclusions
Executes the search and replacement.