Tom
Tom

Reputation: 12998

MySQL query to replace all occurences of a regex in a string

I have a lot of bad data in a table and was hoping there's a query I can use to edit this data.

[{"type":"user","id":"584851"},"2":{"type":"user","id":"180269"},"3":{"type":"user","id":"140535"}]

and here's how I need it to look...

[{"type":"user","id":"584851"},{"type":"user","id":"180269"},{"type":"user","id":"140535"}]

So basically removing all occurrences of ' "2": ' (the number will differ)

Is there a simple query to do this or will I need to write something in php to do the job?

Upvotes: 0

Views: 661

Answers (1)

Ozzy
Ozzy

Reputation: 10643

Unfortunately, MySQL does not have a REGEX_REPLACE function or equivalent that would let you run a simple update query. The next best thing I would suggest is to loop through every record in your table using your language of choice and applying the regex replace on it and saving. I have put an example in PHP below:

$db = new PDO(sprintf('mysql:host=%s;dbname=%s', $host, $dbname), $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->query('select * from `table`');

foreach ($query->fetch(PDO::FETCH_OBJ) as $row) {

    $update = $db->prepare('update `table` set `data` = ? where `id` = ?');
    $update->execute([
        preg_replace('/"\d+":{/', '', $row->data),
        $row->id
    ]);
}

Assumptions have been made about your table structure but the important part of the code is the preg_replace parameter which will match what you need to remove.

Upvotes: 1

Related Questions