简体   繁体   English

MySQL查询替换字符串中所有正则表达式的出现

[英]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) 因此,基本上删除所有出现的“ “ 2”: '(数字会有所不同)

Is there a simple query to do this or will I need to write something in php to do the job? 是否有一个简单的查询来执行此操作,或者我需要在php中编写一些内容来完成这项工作?

Unfortunately, MySQL does not have a REGEX_REPLACE function or equivalent that would let you run a simple update query. 不幸的是,MySQL没有让您运行简单更新查询的REGEX_REPLACE函数或等效函数。 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: 我在下面的PHP中举了一个例子:

$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. 已对表结构进行了假设,但是代码的重要部分是preg_replace参数,它将与您需要删除的参数匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM