我的目标是用万能链接替换数据库中的链接。我通常使用 REPLACE 命令来替换数据库中的字符串,但这次我遇到了困难,因为为了找到我需要使用正则表达式的链接,而这根本行不通:
UPDATE node_revisions SET body = REPLACE ( `body` , 'http://.*.\pdf', '/migration-update' );
UPDATE node_revisions SET teaser = REPLACE ( `teaser` , 'http://.*pdf', '/migration-update' );
这两个查询都落空了。
在这种情况下需要做什么?
最佳答案
正如其他人已经提到的,您不能在 MySQL 中执行此操作。但是,这似乎是您需要执行的一次性操作,因此我为您编写了一个快速但肮脏的小 php 脚本来完成这项工作。它假定您的 node_revisions 表有一个名为“id”的主键列。如果不是,请适当编辑。另外,不要忘记更改脚本顶部的数据库主机、用户名、密码和数据库名称以匹配您的配置。
<?php
$host = '127.0.0.1';
$username = 'root';
$password = 'password';
$database = 'test';
$conn = mysql_connect($host, $username, $password);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db($database)) {
echo "Unable to select " . $database . ": " . mysql_error();
exit;
}
$sql = "SELECT * FROM node_revisions";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$body = $row['body'];
$teaser = $row['teaser'];
$body = preg_replace('/http:\/\/.*?\.pdf/', '/migration-update', $body);
$teaser = preg_replace('/http:\/\/.*?\.pdf/', '/migration-update', $teaser);
$sql = "UPDATE node_revisions set body='" . mysql_real_escape_string($body) . "', teaser='" . mysql_real_escape_string($teaser) . "' where id=" . $id;
mysql_query($sql);
}
mysql_free_result($result);
mysql_close($conn);
?>
另请注意,我在正则表达式上使用了非贪婪修饰符,这样如果您在正文或预告片字段中有多个 pdf 网址,您就不会丢失它们之间的所有内容。
关于mysql - 如何在 MySQL 替换命令中使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384796/